What's wrong with my Insert command

时间:2016-10-20 13:00:24

标签: c# mysql sql database

I'm trying to insert data into my database using a DataGridView in C#. However when I click the save button appears the following error message:

System.Data.OleDb.OleDbException was unhandled

HResult = -2147217900
Message = Syntax error in INSERT INTO statement.
Source = Microsoft Office Access Database Engine
ErrorCode = -2147217900

Here's the code I have:

private void save_btn_Click(object sender, EventArgs e)
{
    OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Stock.accdb");
    con.Open();

    for (int i = 0; i < dataGridView_insert.Rows.Count; i++)
    {
        OleDbCommand cmd = new OleDbCommand("INSERT INTO product(OV,Reference,Cod_Client,Client,Qtd,Type_product,Posicion_product,) VALUES ('" + dataGridView_insert.Rows[i].Cells["OV"].Value + "','" + dataGridView_insert.Rows[i].Cells["Reference"].Value + "','" + dataGridView_insert.Rows[i].Cells["Cod_Client"].Value + "','" + dataGridView_insert.Rows[i].Cells["Client"].Value + "','" + dataGridView_insert.Rows[i].Cells["Qtd"].Value + "','" + dataGridView_insert.Rows[i].Cells["Type_product"].Value + "','" + dataGridView_insert.Rows[i].Cells["Posicion_product"].Value + " ' ", con);    
       cmd.ExecuteNonQuery();    
    }

    con.Close();
}

What is wrong?

1 个答案:

答案 0 :(得分:1)

You have one stray , after Posicion_product and also you missed the closing bracket of VALUES in your insert statement. Remove it. Also you should always use parameterized queries to avoid SQL Injection:

OleDbCommand cmd = new OleDbCommand("INSERT INTO product(OV,Reference,Cod_Client,Client,Qtd,Type_product,Posicion_product) VALUES (@a,@b,@c,@d,@e,@f,@g)", con);
cmd.Parameters.AddWithValue("@a", dataGridView_insert.Rows[i].Cells["OV"].Value);
cmd.Parameters.AddWithValue("@b", dataGridView_insert.Rows[i].Cells["Reference"].Value);
cmd.Parameters.AddWithValue("@c", dataGridView_insert.Rows[i].Cells["Cod_Client"].Value);
//And continue for other parameters

Although specify the type directly and use the Value property is more better than AddWithValue:

cmd.Parameters.Add("@a", SqlDbType.VarChar).Value = dataGridView_insert.Rows[i].Cells["OV"].Value;