2

I am using OleDbParameter to build an OleDbCommand to INSERT a record into MS Access. But I get Syntax Error when I am executing the statement. If anyone can see what is preventing the query successfully executing it would be a huge help.

This is my code:

string query = "INSERT INTO Customer (customerID, date, time, telephone, fax,"
    + "name, sourceAddress, destAddress, via1, via2, via3,"
    + "priority, ourReference) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

OleDbCommand oleDbCommand = new OleDbCommand(query, oleDbConnection);

OleDbParameter customerID = new OleDbParameter();
OleDbParameter date = new OleDbParameter();
OleDbParameter time = new OleDbParameter();
OleDbParameter telephone = new OleDbParameter();
OleDbParameter fax = new OleDbParameter();
OleDbParameter name = new OleDbParameter();
OleDbParameter sourceAddress = new OleDbParameter();
OleDbParameter destAddress = new OleDbParameter();
OleDbParameter via1 = new OleDbParameter();
OleDbParameter via2 = new OleDbParameter();
OleDbParameter via3 = new OleDbParameter();
OleDbParameter priority = new OleDbParameter();
OleDbParameter ourReference = new OleDbParameter();

oleDbCommand.Parameters.Add(customerID);
oleDbCommand.Parameters.Add(date);
oleDbCommand.Parameters.Add(time);
oleDbCommand.Parameters.Add(telephone);
oleDbCommand.Parameters.Add(fax);
oleDbCommand.Parameters.Add(name);
oleDbCommand.Parameters.Add(sourceAddress);
oleDbCommand.Parameters.Add(destAddress);
oleDbCommand.Parameters.Add(via1);
oleDbCommand.Parameters.Add(via2);
oleDbCommand.Parameters.Add(via3);
oleDbCommand.Parameters.Add(priority);
oleDbCommand.Parameters.Add(ourReference);

customerID.Value = 4;
date.Value = "01/01/01";
time.Value = "01:01:01";
telephone.Value = 01010101;
fax.Value = 01010101;
name.Value = "test 4";
sourceAddress.Value = "test 4 source address";
destAddress.Value = "test 4 dest address";
via1.Value = "test 4 via 1";
via2.Value = "test 4 via 2";
via3.Value = "test 4 via 3";
priority.Value = 1;
ourReference.Value = "test 4 ref";

MessageBox.Show(oleDbCommand.CommandText.ToString());

OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(oleDbCommand);

oleDbCommand.CommandText = query;

oleDbConnection.Open();

oleDbCommand.ExecuteNonQuery();
4

3 回答 3

3

字段datetimeJET/Access 的保留字,因此您应该将它们封装在方括号中。(这是语法错误消息的真正来源)

"INSERT INTO Customer (customerID, [date], [time], telephone, fax, name, " + 
"sourceAddress, destAddress, via1, via2, via3," + "priority, ourReference) VALUES " + 
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; 

当然参数的数量应该匹配。(12 个占位符与 13 个字段/参数,添加另一个占位符?),但这会给出另一个错误消息,而不是所述的语法错误

于 2012-09-25T10:11:39.903 回答
1

你有 13 个参数,但只有 12 个?

于 2012-09-25T10:08:22.677 回答
1

正如其他人所提到的,您的参数与占位符不同步,但是,如果您的 CustomerID 是自动编号,那么您可以从 sql 和参数列表中省略它。

于 2012-09-25T10:11:51.757 回答