Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Syntax error in INSERT INTO statement" error when I try to insert date to Access database by C#

I want to insert a date record to an Access database. Here is my code:

cmd.CommandText = "INSERT INTO AlarmHistory(Date) VALUES ('6/8/2012')"; 
cmd.ExecuteNonQuery(); 

It gives Syntax error in INSERT INTO statement. error at second row.

The screenshot that show my cell data type on db is below.

Cell data type at db

like image 336
Ned Avatar asked Dec 26 '22 23:12

Ned


1 Answers

Use parameters

cmd.CommandText = "INSERT INTO AlarmHistory([Date]) VALUES (?)";  
cmd.Parameters.AddWithValue("@date", new DateTime(2012,06,8));
cmd.ExecuteNonQuery();

This will preserve your code from SqlInjection and you could stop to worry about quoting your values-

Just tried creating a dummy database. It's the Date Field. You should enclose in square brackets because Date is a reserved keyword

Here the list of the reserved keywords for Jet 4.0

like image 164
Steve Avatar answered Jan 25 '23 22:01

Steve