将datagridview中的行插入DB时出错

时间:2015-02-01 06:59:49

标签: c#

我正在尝试从datagridview向DB中插入一行。我在命令执行期间遇到了致命的错误'。

如何解决此问题?

这是我的代码

private void BtnSave_Click(object sender, EventArgs e)
{
        string myconnectionstring1 = "Server=localhost; Database=amepos2015; Uid=root; Pwd=fatehshah";
        MySqlConnection con = new MySqlConnection(myconnectionstring1);

        con.Open();

        String str = "INSERT INTO invoice_detail (INVOICE_NO,INVOICE_LINE_NO,BARCODE,PRODUCT_NAME,DESCRIPTION,VENDOR_NAME,UNIT_QTY,UOM,TOTAL_QTY,COST,RETAIL,DISCOUNT,AMOUNT,REGISTERED_DATE,REGISTERED_BY_USER) VALUES (@invoice,@invoice_line_no,@barcode,@product_name,@description,@vendor_name,@unit_qty,@uom,@total_qty,@cost,@retail,@discount,@amount,"+DateTime.Now+","+"AME"+")";

            for(int i = 0; i < dataGridView1.Rows.Count-1; i++)
            {
                   MySqlCommand cmd = new MySqlCommand(str,con);

                   cmd.Parameters.AddWithValue("@invoice_no",dataGridView1.Rows[i].Cells[0].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@invoice_line_no", dataGridView1.Rows[i].Cells[1].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@barcode", dataGridView1.Rows[i].Cells[2].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@product_name", dataGridView1.Rows[i].Cells[3].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@description", dataGridView1.Rows[i].Cells[4].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@vendor_name", dataGridView1.Rows[i].Cells[5].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@unit_qty", dataGridView1.Rows[i].Cells[6].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@uom", dataGridView1.Rows[i].Cells[7].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@total_qty", dataGridView1.Rows[i].Cells[8].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@cost", dataGridView1.Rows[i].Cells[9].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@retail", dataGridView1.Rows[i].Cells[10].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@discount", dataGridView1.Rows[i].Cells[11].FormattedValue.ToString());
                   cmd.Parameters.AddWithValue("@amount", dataGridView1.Rows[i].Cells[12].FormattedValue.ToString());

                   cmd.ExecuteNonQuery();
                   cmd.Parameters.Clear();
            }
            con.Close();     
}

0 个答案:

没有答案