如何添加多个记录从datagridview添加到数据库C# [英] how to add more than one record adding in to database from datagridview c#

查看:86
本文介绍了如何添加多个记录从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆