Msgstr "Syntax error in INSERT INTO statement". What for?

My code is below. I have a method in which I pass three parameters and they are written to the MS Access database table. However, I continue to receive a syntax error message. Can someone tell me why? I got this example from the Internet.

private static void insertRecord(string day, int hour, int loadKW) { string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\LoadForecastDB.accdb"; OleDbConnection conn = new OleDbConnection(connString); string ins = @"INSERT INTO Forecasts (Day, Hour, Load) VALUES (?,?,?)"; OleDbCommand cmd = new OleDbCommand(ins, conn); cmd.Parameters.Add("@day", OleDbType.VarChar).Value = day; cmd.Parameters.Add("@hour", OleDbType.Integer).Value = hour; cmd.Parameters.Add("@load", OleDbType.Integer).Value = loadKW; conn.Open(); try { int count = cmd.ExecuteNonQuery(); } catch (OleDbException ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); } } 
+4
source share
3 answers

I think it could be because your column names (Day and hour) are also keywords. Perhaps you can place around them (inverted single quotes) (which work in MySQL, do not know about MS Access)

+7
source

Try to change

 string ins = @"INSERT INTO Forecasts (Day, Hour, Load) VALUES (?,?,?)"; 

To:

 string ins = @"INSERT INTO Forecasts ([Day], [Hour], [Load]) VALUES (@day, @hour, @load)"; 
+2
source

Another option would be to reference numbers binding variables:

  cmd.Parameters.Add(1, OleDbType.VarChar).Value = day; cmd.Parameters.Add(2, OleDbType.Integer).Value = hour; cmd.Parameters.Add(3, OleDbType.Integer).Value = loadKW; 

Note. I don't know C #, but a similar approach works for Java and JDBC.

0
source

Source: https://habr.com/ru/post/1306215/


All Articles