My code is below. I have a method where I pass in three parameters and they get written out to an MS Access database table. However, I keep getting a syntax error message. Can anyone tell me why? I got this example from the internet.
我的代码如下。我有一个方法,我传入三个参数,然后写入MS Access数据库表。但是,我不断收到语法错误消息。谁能告诉我为什么?我从互联网上得到了这个例子。
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();
}
}
3 个解决方案
#1
7
I think this could be because your column names (Day and Hour) are also keywords. Maybe you can put ` (inverted single quotes) around them (that works in MySQL, don't know about MS Access)
我想这可能是因为您的列名(日和小时)也是关键字。也许你可以把'(倒置的单引号)放在它们周围(在MySQL中有效,不了解MS Access)
#2
2
Try changing
尝试改变
string ins = @"INSERT INTO Forecasts (Day, Hour, Load) VALUES (?,?,?)";
To:
至:
string ins = @"INSERT INTO Forecasts ([Day], [Hour], [Load]) VALUES (@day, @hour, @load)";
#3
0
Another option might be to refer bind variables with numbers:
另一种选择可能是使用数字引用绑定变量:
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 do not know C#, but similar approach works for Java and JDBC.
注意我不知道C#,但类似的方法适用于Java和JDBC。
#1
7
I think this could be because your column names (Day and Hour) are also keywords. Maybe you can put ` (inverted single quotes) around them (that works in MySQL, don't know about MS Access)
我想这可能是因为您的列名(日和小时)也是关键字。也许你可以把'(倒置的单引号)放在它们周围(在MySQL中有效,不了解MS Access)
#2
2
Try changing
尝试改变
string ins = @"INSERT INTO Forecasts (Day, Hour, Load) VALUES (?,?,?)";
To:
至:
string ins = @"INSERT INTO Forecasts ([Day], [Hour], [Load]) VALUES (@day, @hour, @load)";
#3
0
Another option might be to refer bind variables with numbers:
另一种选择可能是使用数字引用绑定变量:
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 do not know C#, but similar approach works for Java and JDBC.
注意我不知道C#,但类似的方法适用于Java和JDBC。