无法从C#保存到MS Access数据库

时间:2017-01-27 09:20:34

标签: c# ms-access

vith cmb的值是一个组合框。当我单击“保存”按钮时,它会抛出错误。

我的代码在这里:

cn.Open();

OleDbCommand command = new OleDbCommand();
command.Connection = cn;
command.CommandText = "insert into TblProductDetails(ProductID, ProductName, Category, Section, UOM, CostPrice, SellingPrice1, SellingPrice2, DiscountPercentage, DiscountAmount, MinimumPrice, Vendor, Stock) values ('" + txtProductID.Text + "','" + txtName.Text + "','" + category + "','" + section + "','" + uom + "','" + txtCostprice.Text + "','" + txtSellingPrice1.Text + "','" + txtSellingPrice2.Text + "','" + txtDiscountpercentage.Text + "','" + txtDiscountAmount.Text + "','" + txtMinimumPrice.Text + "','" + vendor + "','" + txtBeginingStock.Text + "')";

command.ExecuteNonQuery();
cn.Close();

2 个答案:

答案 0 :(得分:0)

可能有很多事情。见史蒂夫的评论。但是您还要检查文本框中“'”字符(撇号)的值,就像文本框中包含该字符一样,这​​也可能导致语法问题,请查看SQL注入以获取更多信息有关的信息。认为这值得一提。您也可以使用DataTableAdapter进行此类操作,或者仅使用Entity Framework清除一点(我会这么做)。

答案 1 :(得分:0)

System.Data.OleDb.OleDbConnection conn = new
            System.Data.OleDb.OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Your DataBasePath";
        conn.Open();
        System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.CommandText = "INSERT INTO TblProductDetails (ProductID, ProductName, Category, Section, UOM, CostPrice, SellingPrice1, SellingPrice2, DiscountPercentage, DiscountAmount, MinimumPrice, Vendor, Stock) VALUES(@ProductID, @ProductName, @Category, @Section, @UOM, @CostPrice, @SellingPrice1, @SellingPrice2, @DiscountPercentage, @DiscountAmount, @MinimumPrice, @Vendor, @Stock)";
        cmd.Parameters.AddWithValue("@ProductID", comboBox1.Text);
        cmd.Parameters.AddWithValue("@ProductName", textBox1.Text);
        cmd.Parameters.AddWithValue("@Category", textBox2.Text);
        cmd.Parameters.AddWithValue("@Section", textBox2.Text);
        cmd.Parameters.AddWithValue("@UOM", textBox4.Text);
        // continue Your Code its just example 
        cmd.Connection = conn;

        cmd.ExecuteNonQuery();
        conn.Close();