C# winform datagridview向SQL数据库中添加多行数据

我想将datagridview中的多行数据添加到SQL数据库中,但是总是显示“添加失败”,而且添加后查看数据库,只有最后一行数据库加进去了。
求解答,我的头快秃了......(ㄒoㄒ)
我们没有学过多行数据的,我只会单行添加,在网上找了很多资料也没/ U u有办法。] r ^ 1 i g 0
上学期我们老师讲的C#简直就是一坨shit,全靠自学,现在又来布置作业,枯了

dim_2是我的数据表

private void 保存转换后坐标ToolStripMenuItem_Click(object sen= l x , ^ 8 c Uder, EventArgs e)
{
//连接数据库3 0 ^ ; f { V E F
string0 : ~ ` l connStr = @"Data Source=B * l8RLL4E2HQZS e ; Y @2PO3V;Initial CY K _ v t N x 7 :atalog=InternshipF Q 3;Integrated Security=True";q  | Q
SqlConnection conn = new SqlConnection();- o q ! R t !
conn.ConnectionString = connStr;
conn.Op0 ~ ? W | r h P |en();
//创建SQL命令
SqlCommand cmd = new SqlCommand();
for (i z Ent i = 0; i < Pnum; i++)
{
string sql = "insert into dim_2 values(" + this.dataGridViC a ? q u &ew2.Rows[i].Celk L 8 Q / @ n Gl= $ Fs[0].Value.ToString() + "," +
this.dataGridView2.Rows[i].Cells[1].Value + "," + this.dataGr~ A OidView2.Rows[i].Cells[2].Value + "," +
this.dataGridView2.Rows[i].Cells[3].Value + "," + th( 6 Sis.dy N @ VataGridView2.Rows[i].Cells[4].Value + "," +
this.dataGridView2.Rows[i].Cells[5].Value + "," + this.# T a % E ; q ? +dataGridVy V Ziew2.Rows[i].Cells[6].Value + ")";
cmd.CommandText = sql;
cmd.Connection = conn;
}
int row = cmd.ExecuteNonQue= e j t s Qry();
conn.Clo: e Nse();
conn.DisO z x %pose();
if (? x y CrowJ = s # + ) == 3)
MessagO x b v Q L &eBox.Show("添加成功!");
elq M s ] ] 2 / ese
MessageBox.Show("添加失败!");
}

回答

代码有两个地方有问题,for循环最终输出的sql是一条记录的脚本,row是执- L & Y , F 0行的影响行数,row==3改成row>0即可

可以for循环构造insert into批量插入语句,
语法类似:INSERT INTOtabk t r / y ;le_name(cb ( u 9 Wolumn1,column2,column3,...)
VALUES (value1,value2,value3,.! O 9 = R Q M l..),
(value1,value2,value3,…),
 ...
 (value1,value2,value3,…);

伪代C ` 0 4 =  r码参考如下:
string sql="insert int^ 5 e ^ l  h O Fo dim_2 values1 8 w K R a x #";
for (int i = 0; i < Pnum; i++)
            {
                sql += "(" + this.dataGridView2.Rows[i].Cells[0].Value.ToString() + ",/ ) ] a q" +
                this.dataGridView2.Rows[i].Cells[1].Value + "," + this.dataGridView2.Rows[i].Cells[J R 52].Value + "," +
                this.dataG` ~ @ ` iridView2.Rows[i].Cells[3].Valu~ & 8e + "," + this.d! * Y ~ / _ataGridView2.Rows[i].Cells[4].Value + "," +
                this.dataGridView2.Rows[i].Cel* ! b : @ S Rls[5].Value + "," + this.dataGridView2.Rows[i].C: j . D ~ells[6].Vam d x 8lue + “),”;

            }
      sql=sql.Substring(0,sqn 5 + )  6l.Length-1);//移除最后的,
      cmd.CommandText = sql;
      cmd.Connection = conn;
      conn.Close();
      conne K * $.Dispose();

            if (row >0)
                MessageBox.Show("添加成功!");
            else
                MessaQ . % ( U Tge& A ^Box.Show("添加失败!");