2013-03-24 65 views
-1

我得到4200 Syntax Error,当我的MS Access数据库执行此代码:语法错误INSERT INTO使用OdbcConnection

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(); 
      } 
     } 
    } 
+2

你确定你有相关的命名空间吗? (也请提供更多详情,欢迎致SO)。 – 2013-03-24 08:53:17

+0

你有相关的命名空间 – anita 2013-03-24 08:56:40

+0

哪一行你会得到错误? – 2013-03-24 08:57:29

回答

6

命名为NOTE领域拥有reserved keyword的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)"; 

编辑我看你使用的是OdbcConnection,这将需要您的参数占位符将使用问号,不带@前缀字符串提供封装它。所以,你的CommandText应该是:

string CommandText = "INSERT INTO SupplierDetails (Supplier, Company, Address, " + 
        "State, Country, Pincode, PhoneNo, MobileNo, Email, Fax, " + 
        "RawMaterials, [Note]) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; 

注意我怎么也删除ID字段和它的参数占位符,因为你说这是一个自动增加字段,因此你不能将针对您自身的价值。 另外请记住,在这种情况下,参数可以通过它们在Parameter集合中的位置来识别。因此,按照commandText预期的正确顺序添加它们非常重要。

+0

在添加方括号周围后注意它显示:错误[07002] [Microsoft] [ODBC Microsoft Access驱动程序]太少参数。预计13. – anita 2013-03-24 09:14:45

+0

退出自动增加字段,它不是由你来计算。 – Steve 2013-03-24 09:23:46

+0

即使删除此行后cmd.Parameters.AddWithValue(“@ ID”,TextBox3.Text);它显示相同的错误,即ERROR [07002] [Microsoft] [ODBC Microsoft Access Driver]参数太少。预期13. – anita 2013-03-24 09:31:29