如何添加多个记录从datagridview添加到数据库C# [英] how to add more than one record adding in to database from datagridview c#
问题描述
我尝试了以下代码.但是我只能添加一行记录添加到mysql数据库中.我输入了三行记录,但仅添加了一行记录.
是以下代码的问题,请任何人可以帮助我解决这个问题.
i tried below code.but i could add one row record only added in to mysql database. i entered three rows records but only one row records only added.what
is the problem of the below code please any one can help me this problem.
for(int i = 0; i< dataGridView1.Rows.Count; i ++)
{
MySqlCommand cmd =新的MySqlCommand();
cmd.Connection = con;
cmd.CommandText =插入salesproductnew(salesid,productname,qty,price,grosstotal)值(@ 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(已添加记录..........."); con.Close();
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();
推荐答案
似乎数据库一直在打开.将cmd.Connection移动到包含行MySqlCommand的for循环之前.
It seems to that the database is constantly opened. Move the cmd.Connection before the for loop including the line MySqlCommand.
也许有帮助.
关于Rinaldo
这篇关于如何添加多个记录从datagridview添加到数据库C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!