4200 Syntax Error当我为MS Access数据库执行此代码时,我得到:
protected void Button1_Click(object sender, EventArgs e)
{
using (OdbcConnection conn = new OdbcConnection(@"Dsn=ani;dbq=D:\anita\inventory\chemicals.accdb;defaultdir=D:\anita\inventory;driverid=25;fil=MS Access;maxbuffersize=2048;pagetimeout=5;uid=admin"))
{
conn.Open();
string CommandText = "INSERT INTO SupplierDetails (ID, Supplier, Company, Address, State, Country, Pincode, PhoneNo, MobileNo, Email, Fax, RawMaterials, Note) VALUES (@ID, @Supplier, @Company, @Address, @State, @Country, @Pincode, @PhoneNo, @MobileNo, @Email, @Fax, @RawMaterials, @Note)";
using (OdbcCommand cmd = new OdbcCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("@ID", TextBox3.Text);
cmd.Parameters.AddWithValue("@Supplier", TextBox4.Text);
cmd.Parameters.AddWithValue("@Company", TextBox1.Text);
cmd.Parameters.AddWithValue("@Address", TextBox11.Text);
cmd.Parameters.AddWithValue("@State", TextBox2.Text);
cmd.Parameters.AddWithValue("@Country", TextBox5.Text);
cmd.Parameters.AddWithValue("@Pincode", TextBox10.Text);
cmd.Parameters.AddWithValue("@PhoneNo", TextBox6.Text);
cmd.Parameters.AddWithValue("@MobileNo", TextBox7.Text);
cmd.Parameters.AddWithValue("@Email", TextBox8.Text);
cmd.Parameters.AddWithValue("@Fax", TextBox9.Text);
cmd.Parameters.AddWithValue("@RawMaterials", TextBox12.Text);
cmd.Parameters.AddWithValue("@Note", TextBox13.Text);
cmd.ExecuteNonQuery();
}
}
}
Run Code Online (Sandbox Code Playgroud)
命名字段NOTE与JET 4.0 中的保留关键字具有相同的名称.
用方括号封装它
string CommandText = "INSERT INTO SupplierDetails (ID, Supplier, Company, Address, " +
"State, Country, Pincode, PhoneNo, MobileNo, Email, Fax, " +
"RawMaterials, [Note]) VALUES (@ID, @Supplier, @Company, @Address, " +
"@State, @Country, @Pincode, @PhoneNo, @MobileNo, @Email, " +
"@Fax, @RawMaterials, @Note)";
Run Code Online (Sandbox Code Playgroud)
编辑我看到你正在使用OdbcConnection,这将要求你的参数占位符将使用问号,而不是带有@前缀的字符串.所以你的CommandText应该是:
string CommandText = "INSERT INTO SupplierDetails (Supplier, Company, Address, " +
"State, Country, Pincode, PhoneNo, MobileNo, Email, Fax, " +
"RawMaterials, [Note]) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
Run Code Online (Sandbox Code Playgroud)
请注意我是如何删除ID字段及其参数占位符的,因为您说它是一个AutoIncrement字段,因此您无法为其传递自己的值.还要记住,在这种情况下,参数可以通过它们在Parameter集合中的位置来识别.因此,以commandText所期望的正确顺序添加它们非常重要.