简体   繁体   中英

Couldn't save to MS Access database from C#

The values staring vith cmb is a combo box. When I click the save button, it throws an error.

My code is here:

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

It could be many things. See comment from Steve. But you also want to check the values in the text boxes for the " ' " character (apostrophe) as if the text box contains that character then that could also cause syntax issues, check out SQL injection for more information on that. Thought this was worth a mention. You could use a DataTableAdapter for this kind of thing too, or Entity Framework just to clear that up a little (I would do).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM