I get date from DateEdit and try to Store into Access Database. But it show error like this
Syntax error in INSERT INTO statement.
my insert statement is this
OleDbCommand top = new OleDbCommand("INSERT INTO invoice(invoice_number,order_number,customername,status,subtotal,tax,total,date) VALUES (" + inno + "," + odrno + ",'" + name + "','"+ chk1 +"' ,"+ subtottal +","+ tax +","+total+",'"+date+"')", conn);
top.ExecuteNonQuery();
Except Date remaining values store successfully but how can i store date ??
I get date like this DateTime date = dateEdit1.DateTime;
Help me.
DATE is a reserved keyword for Microsoft Access. You shoud use it with square brackets like [DATE]
And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
OleDbCommand top = new OleDbCommand(#"INSERT INTO invoice(invoice_number,order_number,customername,status,subtotal,tax,total,[date])
VALUES (#invoice_number, #order_number, #customername, #status, #subtotal, #tax, #total, #date)", conn);
top.Parameters.AddWithValue("#invoice_number", inno);
top.Parameters.AddWithValue("#order_number", odrno);
top.Parameters.AddWithValue("#customername", name);
top.Parameters.AddWithValue("#status", chk1);
top.Parameters.AddWithValue("#subtotal", subtotal);
top.Parameters.AddWithValue("#tax", text);
top.Parameters.AddWithValue("#total", total);
top.Parameters.AddWithValue("#date", date);
As a general recommendation, don't use reserved keywords for your identifiers and object names in your database.
Related
I am facing a problem on passing the DateTime.Now into Access database:
oleDBCommand.CommandText =
"INSERT INTO tblData "([PIC], [Sampling Date]) "VALUES (#PIC, #SamplingDate)";
oleDBCommand.Parameters.Add(new OleDbParameter("#PIC", combobox1.Text));
oleDBCommand.Parameters.Add(new OleDbParameter("#SamplingDate", DateTime.Now));
I tried a lot of methods from the internet like using oleDBType.Date, DateTime.Now.ToString(), using AddWithValue..... And none of it is working.
Note 1: Database setting [Sampling Date] = Data Type: Date/Time (Format - Long Time), database was
Note 2: Below code was working but I prefer to using .parameters as it look much more organize and easy to manage.
oleDBCommand.CommandText =
"INSERT INTO tblData ([PIC], [Sampling Date]) " VALUES ('" + combobox1.Text + "', '" + DateTime.Now + "')";
You dont need to pass parameter when specifying current date.
Let the ms access sql query handle it, you need to replace #SamplingDate parameter to Date() for example
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, Date())";
Here is the best explanation Insert today's date
I was struggling with this this week and the accepted answer really did not help me. I found that if I did the assignment of the date+time as an ODBC canonical string (yyyy-mm-dd hh:mi:ss), it worked just fine. So, my C# code looked something like:
InsertCommand.Parameters.Add("#" + column.ColumnName, OleDbType.DBTimeStamp).Value = DateTime.Now.ToString("u");
for the first row and then
InsertCommand.Parameters.Add("#" + column.ColumnName).Value = DateTime.Now.ToString("u")
for the rest.
Try This,
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, #SamplingDate)";
cmd.Parameters.Add("#PIC",OleDbType.VarChar).Value = combobox1.Text;
cmd.Parameters.Add("#PIC", OleDbType.Date).Value = DateTime.Now;
c# ms-access
DateTime myDateTime = Convert.ToDateTime(rd2[0].ToString())
values = myDateTime.ToString("yyyy-MM-dd HH:mm:ss") + " , " + rd2[1].ToString()+ " , " + rd2[2].ToString()+ " , " + rd2[3].ToString()+ " , " + rd2[4].ToString()+ " , " + rd2[5].ToString() ;
i am trying to insert date 2016-04-22 12:58:11 in sql server table of datatype datetime but it gives error "Incorrect syntax near 12"
The string you end up with is similar to this:
2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00
Inserting that into a SQL statement is invalid. You need to wrap each date in single quotes so that you have:
'2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00'
Either way this makes your life difficult and makes your code subject to sql injection and insecure. Consider using parameters like this.
string exampleSQL = "SELECT * from mydatetable where dateOne = #date1 and dateTwo = #date2";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#date1", SqlDbType.DateTime).Value = myDateTime;
command.Parameters.Add("#date2", SqlDbType.DateTime).Value = rd2[1];
This way you dont need to worry about formatting. The system automatically will replace the #date1 and #date2 with the values you specified and it will deal with adding the nescessary structure of the SQL without you having to worry about it.
I strongly suggest using "parametrizing your sql queries"...For example, you can check it out here:
http://www.dreamincode.net/forums/topic/268104-the-right-way-to-query-a-database-parameterizing-your-sql-queries/
Cheers!
I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?
EDIT:
When I run:
"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
I get:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
[Edit: added "select" before references to last_insert_id()]
What about running "select last_insert_id();" after your insert?
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "
+ bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ");";
+ "select last_insert_id();"
int id = Convert.ToInt32(comm.ExecuteScalar());
Edit: As duffymo mentioned, you really would be well served using parameterized queries like this.
Edit: Until you switch over to a parameterized version, you might find peace with string.Format:
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
Use LastInsertedId.
View my suggestion with example here: http://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/
It bothers me to see anybody taking a Date and storing it in a database as a String. Why not have the column type reflect reality?
I'm also surprised to see a SQL query being built up using string concatenation. I'm a Java developer, and I don't know C# at all, but I'd wonder if there wasn't a binding mechanism along the lines of java.sql.PreparedStatement somewhere in the library? It's recommended for guarding against SQL injection attacks. Another benefit is possible performance benefits, because the SQL can be parsed, verified, cached once, and reused.
Actually, the ExecuteScalar method returns the first column of the first row of the DataSet being returned. In your case, you're only doing an Insert, you're not actually querying any data. You need to query the scope_identity() after you're insert (that's the syntax for SQL Server) and then you'll have your answer. See here:
Linkage
EDIT: As Michael Haren pointed out, you mentioned in your tag you're using MySql, use last_insert_id(); instead of scope_identity();
when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}
The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).
Looks like you need:
insert into table values(#time)
Without the single character quote.
Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.
I am trying to insert a record to a mysql database using c# but I always saw this error message:
You have error in your SQL syntax;check the manual that corredponds to
your MySQL server version for the right syntax to use near
'Order(idOrder, Quantity, Date, Menu_idMenu)VALUES(10002,
'1', '3/17/2013 12:00' at line 1
this is the code:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
com.CommandText = "INSERT INTO Order (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
int insert = com.ExecuteNonQuery();
}
}
what does it mean?
You have reserved keywords in your query, Order. Quote it and be happy.
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
Also, it is good practice to use parameters.
Date and Order are reserved keywords on MySQL.
Use them between ''
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
And always use parameterized queries. This kind of codes open for an SQL Injection attacks.
Actually, you can use Date without quotes.
MySQL permits some keywords to be used as unquoted identifiers because
many people previously used them.
Since, I suggest you using parameterized queries, here how you can use it with your code;
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (#idOrder, #Quantity, #Date, #Menu_idMenu)";
com.Parameters.AddWithValue("#idOrder", "10002");
com.Parameters.AddWithValue("#Quantity", row.Cells[0].Value.ToString());
com.Parameters.AddWithValue("#Date", DateTime.Today.ToString());
com.Parameters.AddWithValue("#Menu_idMenu", row.Cells[1].Value.ToString());