使用OdbcConnection在INSERT INTO中出现语法错误

时间:2013-03-24 08:47:27

标签: sql ms-access

当我为MS Access数据库执行此代码时,我得到4200 Syntax Error

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

1 个答案:

答案 0 :(得分:6)

名为NOTE的字段与JET 4.0中的reserved keyword具有相同的名称 用方括号将其封装

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字段及其参数占位符的,因为您说它是一个AutoIncrement字段,因此您无法为其传递自己的值。 还要记住,在这种情况下,参数可以通过它们在Parameter集合中的位置来识别。因此,以commandText所期望的正确顺序添加它们非常重要。