如何从datagridview c#添加多个记录添加到数据库

时间:2017-05-03 14:29:39

标签: c#

我尝试了下面的代码,但我可以添加一行记录,只添加到mysql数据库中。我输入了三行记录,但只添加了一行记录。有什么问题?

for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {

      MySqlCommand cmd = new MySqlCommand();
      cmd.Connection = con;

      cmd.CommandText = "insert into salesproductnew(salesid,productname,qty,price,grosstotal)values(@salesid,@productname,@qty,@price,@grosstotal)";


      cmd.Parameters.AddWithValue("@salesid", lbinvoice.Text);
      cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
      cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
      cmd.Parameters.AddWithValue("@price", dataGridView1.Rows[i].Cells[4].Value);
      cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[5].Value);

      con.Open();
      cmd.ExecuteNonQuery();

      MessageBox.Show("Record added .............");
      con.Close();

    }

1 个答案:

答案 0 :(得分:0)

您没有重置cmd的参数,而是在每个周期添加新参数。可能不是直接回答,但试试这个

MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "insert into salesproductnew(salesid,productname,qty,price,grosstotal)values(@salesid,@productname,@qty,@price,@grosstotal)";
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
  cmd.Parameters.Clear();
  cmd.Parameters.AddWithValue("@salesid", lbinvoice.Text);
  cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
  cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
  cmd.Parameters.AddWithValue("@price", dataGridView1.Rows[i].Cells[4].Value);
  cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[5].Value);

  cmd.ExecuteNonQuery();

}

  MessageBox.Show("Record added .............");
  con.Close();

顺便说一句,您不必清除参数。有关详细信息,请参阅this SO