I am trying to insert data into my database table using the insert statement as shown below:
private void buttonPurchase_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Purchase?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
////store invoice
string connectionString = ConfigurationManager.ConnectionStrings
["CarDBConnectionString"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [dbo].[invoiceTbl] ([invoiceId], [dateAndTime]) VALUES (2, N'2014-06-22 00:00:00')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
but although no errors were shown, the code works, the data inserted is not showing up in my table data. I tried adding them manually in the table, and copied the sql statement directly into the code shown above, when I add in duplicate data it is detected, but when I add in data again (without duplicating the primary key) the table data shows NULL and NULL respectively. So in short I think my code works, but for some weird reason it just doesn't show up in my schema! Any help is deeply appreciated! :)
Related
I have a query in the access database that appends email addresses from one table to another. In the source table there may be many duplicated emails. In the target table the email field is unique. Before running the query, there may already in the target table emails that are in the source table.
When running the query manually, I get a message about duplicates and I have to click on Yes to run the query anyway.
But when I try to run the query from the asp.net, c#, I get an exception and nothing is done.
How can I override the exception? I mean, how can I "tell" the system to assume I clicked on Yes after the warning?
Here is my code:
public static void RunQuery(string db, string command)
{
OleDbConnection conn = getConn(db); //set the value for conn
try
{
if (conn != null) conn.Close();
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = command; // query name
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception e)
{
log.Error(e);
throw;
}
finally
{
if (conn != null)
conn.Close();
}
}
Thanks
It has never been clear when/how the error msg of duplicates will trigger.
I find that this (in most cases) will run the append query, and errors are ignored.
This:
// run append query
using (OleDbConnection conn =
new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL =
new OleDbCommand("AddToHotelss", conn))
{
conn.Open();
cmdSQL.CommandType = CommandType.StoredProcedure;
cmdSQL.ExecuteNonQuery();
}
}
Now, the above runs this saved query in Access:
INSERT INTO tblHotels2 ( FirstName, LastName, HotelName, EmailName )
SELECT tblHotels.FirstName, tblHotels.LastName, tblHotels.HotelName,
tblHotels.EmailName
FROM tblHotels
WHERE (tblHotels.City = "Edmonton");
And I have a unique index on EmailName - and the above works.
So, give the "setting" of CommandType = StoredProcedure.
The above SHOULD work.
If it does not?
Then you have to consider introduction of the office.interop ACE data engine. (I don't think that's a good idea).
Or, if above idea does not work?
You have to modify your query to prevent duplicates in the first place..
The query then becomes this:
INSERT INTO tblHotels2 ( FirstName, LastName, HotelName, EmailName )
SELECT tblHotels.FirstName, tblHotels.LastName, tblHotels.HotelName,
tblHotels.EmailName
FROM tblHotels
WHERE (tblHotels.City="Edmonton")
AND
(tblHotels.EmailName NOT IN (SELECT EmailName from tblHotels2.EmailName));
So, as suggested, you re-write the query to never allow duplicates.
I would however give the commandText setting (StoredProcedure) as per above - since in the past I had that work for me. (the duplicates message did not trigger, or stop the append).
I wanted to insert values into database but it is not working eventhough my code perfectly working when its used as stored procedure. I am trieng to use button click to store the value. Please tell whats wrong with the code. Its not showing any error or exception but data is not getting updated in the table
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES ('12', 'abcd', '20')";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
my columns acnum and shares_bought are "int" and scripname is
"varchar"
Then you will not need single quotes for your integer values. Use it as;
...VALUES (12, 'abcd', 20)"
A few things more;
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
You don't need cmd.CommandType = CommandType.Text line. It is .Text by default.
var conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
using(var sqlConnection1 = new SqlConnection(conStr))
using(var cmd = sqlConnection1.CreateCommand())
{
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES (12, 'abcd', 20)";
sqlConnection1.Open();
cmd.ExecuteNonQuery();
}
Set breakpoint in code and see if code is executing. In case you don't know how to, see here.
As you are not getting any exception on insert statement and it's not reflecting in database, either you have different connection string or your code is not getting executed.
I need to find all the multiple or non-autoincremented primary keys, make them normal keys, and make the primary key an autoincrement column. But I need to check if there is already an autoincrement column, so I make that one a primary key, in case if it's not.
Based on this Microsoft article on How To Retrieve Column Schema by Using the DataReader GetSchemaTable Method and Visual C# .NET I have written a little code for you to pick the field with the auto increment set to True,
OleDbConnection cn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
DataTable schemaTable;
OleDbDataReader myReader;
//Open a connection to the SQL Server Northwind database.
cn.ConnectionString = "...";
cn.Open();
//Retrieve records from the Employees table into a DataReader.
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM Employees";
myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
//Retrieve column schema into a DataTable.
schemaTable = myReader.GetSchemaTable();
var myAutoIncrements = schemaTable.Rows.Cast<DataRow>().Where(
myField => myField["IsAutoIncrement"].ToString() == "True");
foreach (var myAutoInc in myAutoIncrements)
{
Console.WriteLine((myAutoInc[0]));
}
Console.ReadLine();
//Always close the DataReader and connection.
myReader.Close();
cn.Close();
You can simply paste this on you app or even a new console app and see the results of shown Fields with the IsAutoIncrement set to true.
OleDbReader has a GetSchemaTable method. You can call that with a basic select to each table, then loop through the returned columns and check for IsAutoIncrement.
https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getschematable(v=vs.110).aspx
Sorry for my vague-ish title. Basically, I have a Call Logging app that uses a database with 2 tables (Customer and Records) to add, remove and search for records. I have a column in Records called 'CallID' that I use to help keep the calls unique and so I can use the CallID to Remove specific records. However, the problem lies on my adding call function. I currently have it so that the CallID is the number of items in the list incremented by 1:
private void addcall_btn_Click(object sender, EventArgs e)
{
try
{
//This is my addcall click event that inserts a row in 'Records' table using what the user has entered into the fields
string sql = "INSERT Records (CustomerID, CallID, CustomerName, Telephone, DateAndTime, Status, Description) VALUES (#CustomerID, #CallID, #CustomerName, #Telephone, #DateAndTime, #Status, #Description)";
SqlConnection conn = ConnectionString();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("CustomerID", customerID_cb.Text);
cmd.Parameters.AddWithValue("CallID", (CallListBox.Items.Count + 1));
cmd.Parameters.AddWithValue("DateAndTime", DateTime.Now);
cmd.Parameters.AddWithValue("Status", status_cb.Text);
cmd.Parameters.AddWithValue("Description", description_txt.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Record Created");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You probably know by now that simply incrementing one to the number of items in the list is a clumsy way of doing things and it leads to problems after records have been removed and you want to add more. I want to know if there is a way to do what I am trying to do but in a much better way :)
Thanks!
Set CallID to auto increment
ALTER TABLE Records AUTO_INCREMENT=1
Then change your insert statement so that it excludes the field
INSERT Records (CustomerID, CustomerName, Telephone, DateAndTime, Status, Description) VALUES (#CustomerID, #CustomerName, #Telephone, #DateAndTime, #Status, #Description)
The value for the CallID field will then be handled by the database for any subsequent rows added.
Proceed in this way(Incase if you're not using auto increment in database), it may help you.
Bind your last value into label or textbox,
SqlConnection con = new SqlConnection("Your Connection String");
con.Open();
SqlCommand cmd = new SqlCommand("Select Max(CallID) from Yourtablename",con);
SQlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
Label1.Text = dr.GetInt32(0).ToString();
}
con.Close();
Change like this in your above code,
cmd.Parameters.AddWithValue("CallID", Convert.ToInt32(Label1.Text));
Make a datatype to int of your CallID column.
Please let me know the further issues.
I'm trying to switch come of my SQL queries to parameter queries but i keep getting some errors shown after the code below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Define data objects
SqlConnection conn;
//SqlCommand comm;
//Read the connection string from web config
string connectionString = ConfigurationManager.ConnectionStrings["clientsConnectionString"].ConnectionString;
//Initialize the connection
conn = new SqlConnection(connectionString);
//Create Command
// comm = new SqlCommand();
const string SQL = "insert into request (Surname,[Other Names], mobileno, date, email, faculty, dept, [Registration Number], session, thesis, yearGrad, tellerno, amount, address, question ) values (#Surname,[#Other Names],#mobileno,#date, #email, #faculty, #dept, [#Registration Number], #session,#thesis, #yearGrad, #tellerno, #amount, #address,#question)";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("#Surname", lblSurname.Text);
cmd.Parameters.AddWithValue("#[Other Names]", lblOtherNames.Text);
cmd.Parameters.AddWithValue("#mobileno", lblPhone.Text);
cmd.Parameters.AddWithValue("#date", lblDate.Text);
cmd.Parameters.AddWithValue("#email", lblEmail.Text);
cmd.Parameters.AddWithValue("#faculty", lblFaculty.Text);
cmd.Parameters.AddWithValue("#dept", lblDept.Text);
cmd.Parameters.AddWithValue("#[Registration Number]", lblRegNo.Text);
cmd.Parameters.AddWithValue("#session", lblSession.Text);
cmd.Parameters.AddWithValue("#thesis", lblThesis.Text);
cmd.Parameters.AddWithValue("#yearGrad", lblGradYr.Text);
cmd.Parameters.AddWithValue("#tellerno", lblTeller.Text);
cmd.Parameters.AddWithValue("#amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#address", lblAdd.Text);
cmd.Parameters.AddWithValue("#question", lblQue.Text);
conn.Open();
// verify if the ID entered by the visitor is numeric
cmd.ExecuteNonQuery();
conn.Close();
//reload page if query executed succesfully
Response.Redirect("thanks.aspx");
}
}
Error message is:
Server Error in '/TranscriptReloaded' Application.
Incorrect syntax near 'nvarchar'.
Must declare the scalar variable "#date".
"date" is a SQL reserved word, so the translation to SQL may be having a problem with it. Generally speaking you should avoid using the word date on its own as column names or as parameters.
Personally I would start by losing the #[two word] variable names (which you also use as [#two word] elsewhere). I don't know if this is the cause, but I have never seen this usage personally, and I'm dubious. Fine for column names (and table names), but variables? Not so sure. Changing the variable names is local to this code, so shouldn't cause any side-effects.