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

dim_2是我的数据表

private void 保存转换后坐标ToolStripMenuItem_Click(object sender, EventArgs e)
       {
           //连接数据库
           string connStr = @"Data Source=8RLL4E2HQZ2PO3V;Initial Catalog=Internship;Integrated Security=True";

           SqlConnection conn = new SqlConnection();
           conn.ConnectionString = connStr;
           conn.Open();
           //创建SQL命令
           SqlCommand cmd = new SqlCommand();
           for (int i = 0; i < Pnum; i++)
           {
               string sql = "insert into dim_2 values(" + this.dataGridView2.Rows[i].Cells[0].Value.ToString() + "," +
               this.dataGridView2.Rows[i].Cells[1].Value + "," + this.dataGridView2.Rows[i].Cells[2].Value + "," +
               this.dataGridView2.Rows[i].Cells[3].Value + "," + this.dataGridView2.Rows[i].Cells[4].Value + "," +
               this.dataGridView2.Rows[i].Cells[5].Value + "," + this.dataGridView2.Rows[i].Cells[6].Value + ")";
               cmd.CommandText = sql;
               cmd.Connection = conn;
           }

           int row = cmd.ExecuteNonQuery();

           conn.Close();
           conn.Dispose();

           if (row == 3)
               MessageBox.Show("添加成功!");

           else
               MessageBox.Show("添加失败!");

       }


  • TIMI    2020-07-01 16:30:11
  • 阅读 1605    收藏 0    回答 1
  • 邀请
  • 收藏
  • 分享
发送
登录 后发表评论
  • 51testing软件测试圈微信