【问题标题】:Insert all data of a datagridview to database at once一次将datagridview的所有数据插入数据库
【发布时间】:2012-05-20 08:34:03
【问题描述】:

我有一个数据网格视图,它是由各种操作和用户对数据的操作创建的。 我想一次将gridview的所有数据插入数据库,我知道我可以尝试类似这样的代码:

for(int i=0; i< dataGridView1.Rows.Count;i++)
    {
        string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";

      try
      {
        using (SqlConnection conn = new SqlConnection(ConnString))
        {
            using (SqlCommand comm = new SqlCommand(StrQuery, conn))
            {
                conn.Open();
                comm.ExecuteNonQuery();
            }
        }
      }

但是每次插入记录时都创建一个新连接是否公平?数据网格可能包含很多行...有什么方法可以一次将所有数据取出到服务器并在sql中循环以插入所有数据?

【问题讨论】:

    标签: c# sql-server winforms


    【解决方案1】:

    如果您移动您的 for 循环,您将不必建立多个连接。只需快速编辑您的代码块(绝不完全正确):

    string StrQuery;
    try
    {
        using (SqlConnection conn = new SqlConnection(ConnString))
        {
            using (SqlCommand comm = new SqlCommand())
            {
                comm.Connection = conn;
                conn.Open();
                for(int i=0; i< dataGridView1.Rows.Count;i++)
                {
                    StrQuery= @"INSERT INTO tableName VALUES (" 
                        + dataGridView1.Rows[i].Cells["ColumnName"].Text+", " 
                        + dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
                    comm.CommandText = StrQuery;
                    comm.ExecuteNonQuery();
                }
            }
        }
    }
    

    关于一次执行多条SQL命令,请看这个链接: Multiple statements in single SqlCommand

    【讨论】:

    • 如果我有 Datagrid 而不是 DataGridView ".Cells is not avaialbe"
    【解决方案2】:

    我认为最好的方法是使用TableAdapters 而不是使用命令对象,它的更新方法将数据集或数据表中的所有更改(更新、插入和删除)直接发送到数据库。通常在使用 DataGridView 时,您绑定到 BindingSource,它允许您与 DataSource(如 Datatables 或 Datasets)进行交互。

    如果你是这样工作的,那么在你的有界 DataGridView 上你可以这样做:

    this.customersBindingSource.EndEdit();
    this.myTableAdapter.Update(this.myDataSet.Customers);
    

    “customersBindingSource”是 DataGridView 的数据源。

    适配器的 Update 方法将更新单个数据表和 执行正确的命令(INSERT、UPDATE 或 DELETE) 表中每个数据行的 RowState。

    发件人:https://msdn.microsoft.com/en-us/library/ms171933.aspx

    因此,在使用 Update 方法时,在 DatagridView 中所做的任何更改都将反映在数据库中。

    更多关于 TableAdapters:https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx

    【讨论】:

    • 这是更好的答案,因为它利用了表适配器的原生特性
    • 如果用户搜索一个特定的ID怎么办,所以它在datagridview中只显示1行记录。然后,他使用 this.myTableAdapter.Update() 对该记录进行了更改和更新。它会更新数据库中的特定记录还是替换数据库只存储那1行记录?
    【解决方案3】:

    请看下面是否对你有帮助

    类 Post_Sales

    Public Shared Sub Post_sales()
    
        Dim ITM_ID As Integer
    
        Dim SLS_QTY As Integer
    
        Dim SLS_PRC As Double
    
        Dim SLS_AMT As Double
    
        Dim DSPL_RCT As String
    
        Dim TAX_CODE As Integer
    
    
        'Format the current  date and send it to a textbox
        Form1.TextBox6.Text = System.DateTime.Now.ToString((" yyyy-MM-dd"))
    
        'Open Connection
    
        Dim con As New SqlConnection("Initial Catalog=Your Database here;Data source=.;Network Library=DBMSSOCN;User ID=sa;Password=")
    
        con.Open()
    
        'Insert Records into the database
    
    
        For Each rw As DataGridViewRow In Form1.DataGridView1.Rows
    
            ITM_ID = rw.Cells("Column1").Value
            DSPL_RCT = rw.Cells("Column2").Value
            SLS_QTY = rw.Cells("Column3").Value
            SLS_PRC = rw.Cells("Column4").Value
            SLS_AMT = rw.Cells("Column5").Value
            TAX_CODE = rw.Cells("Column6").Value
    
            Dim cmd As New SqlCommand("INSERT INTO DAY_PLUSALES (DT,ITM_ID,DSPL_RCT,SLS_QTY,SLS_PRC,SLS_AMT,TAX_CODE) values ('" & Form1.TextBox6.Text & "','" & ITM_ID & "','" & DSPL_RCT & "','" & SLS_QTY & "','" & SLS_PRC & "','" & SLS_AMT & "','" & TAX_CODE & "')", con)
    
            cmd.ExecuteNonQuery()
    
        Next
    
        con.Close()
    
        MessageBox.Show("Records Added to the SQL Database successfully!", "Records Updated ")
    
    End Sub
    

    结束类

    【讨论】:

    • 但是上面的代码是在SQL数据库表中插入一个空白行,请帮忙
    • 我在循环中添加了一个检查
    • If rw.Cells("Column2").Value Nothing Then
    【解决方案4】:

    您可以对只打开一次的连接执行相同的操作。像这样。

    for(int i=0; i< dataGridView1.Rows.Count;i++)
      {
        string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";
    
      try
      {
          SqlConnection conn = new SqlConnection();
          conn.Open();
    
              using (SqlCommand comm = new SqlCommand(StrQuery, conn))
              {
                  comm.ExecuteNonQuery();
              }
          conn.Close();
    
      }
    

    此外,根据您的具体情况,您可能需要考虑将网格绑定到数据库。这将大大减少手工工作量: http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database

    【讨论】:

      【解决方案5】:

      您有语法错误请尝试以下语法:

      string StrQuery="INSERT INTO tableName VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "',' " + dataGridView1.Rows[i].Cells[1].Value + "', '" + dataGridView1.Rows[i].Cells[2].Value + "', '" + dataGridView1.Rows[i].Cells[3].Value + "',' " + dataGridView1.Rows[i].Cells[4].Value + "')";
      

      【讨论】:

        【解决方案6】:

        试试这个 100% 工作代码

        string SQL = "", tableName = "tableName";
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            SQL = @"INSERT INTO " + tableName + " VALUES (";
            for (int col = 0; col < dataGridView1.ColumnCount; col++)
            {
                string data = "";
                if (dataGridView1.Rows[i].Cells[col].Value != null)
                {
                    data = dataGridView1.Rows[i].Cells[col].Value.ToString();
                }
                SQL += "'" + data.Trim() + "'";
                if (col < dataGridView1.ColumnCount - 1)
                {
                    SQL += ",";
                }
            }
            SQL += ")";
            string finalSQL = SQL;
            //INSERT to DB the finalSQL
        }
        

        您的数据现在已准备就绪,通过您的连接将 finalSQL 插入您的数据库中

        【讨论】:

          【解决方案7】:
          try
          {
              string barcode = "", name = "";
              int qty = 0, unitprice = 0;
              for (int i = 0; i < dataGridView1.Rows.Count; i++)
              {
                 barcode= dataGridView1.Rows[i].Cells["barcode"].Value.ToString();
                  name = dataGridView1.Rows[i].Cells["name"].Value.ToString();
                  qty = Int32.TryParse(dataGridView1.Rows[i].Cells["stkqty"].Value.ToString(),out qty)?qty:0;
                  unitprice = Int32.TryParse(dataGridView1.Rows[i].Cells["unitprice"].Value.ToString(),out unitprice)?unitprice:0;
                  SqlConnection conn = new SqlConnection(urls);
                  conn.Open();
                  String insertquery = "INSERT INTO Stock_Sale_Record(invoiceno,barcode,saleqty,proname,saleprice,duedate) VALUES (@invoiceno,@barcode,@saleqty,@proname,@saleprice,@duedate)";
                  SqlCommand insertcommand = new SqlCommand(insertquery, conn);
                  insertcommand.Parameters.AddWithValue("@invoiceno", invoicenolabel.Text.ToString());
                  insertcommand.Parameters.AddWithValue("@barcode", barcode);
                  insertcommand.Parameters.AddWithValue("@saleqty", qty);
                  insertcommand.Parameters.AddWithValue("@proname", name);
                  insertcommand.Parameters.AddWithValue("@saleprice", unitprice);
                  insertcommand.Parameters.AddWithValue("@duedate", duedatetxt.Value.Date);
                  insertcommand.ExecuteNonQuery();
                  conn.Close();
              }
          }
          catch (Exception ex)
          {
              MessageBox.Show(""+ex.Message);
          }
          

          【讨论】:

          • 欢迎来到 StackOverflow。我建议将conn.Close() 移动到finally 块中,以确保即使出现异常也关闭连接。
          【解决方案8】:
          for (int i = 0; i < dataGridView2.Rows.Count; i++)
          {
          SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
                                  SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
                                  cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
                                  cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
                                  cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
                                  cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
                                  cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
                                  cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
                                  cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
                                  cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
                                  cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
                                  cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
                                  cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
                                  con.Open();
                                  cmd.ExecuteNonQuery();
                                  con.Close();
                                  MessageBox.Show("Added successfully!");
          

          【讨论】:

          • 这段代码仍然为每次插入创建一个新的数据库连接。
          猜你喜欢
          • 2014-07-09
          • 2015-05-06
          • 1970-01-01
          • 1970-01-01
          • 2012-08-09
          • 1970-01-01
          • 1970-01-01
          • 2013-03-01
          • 2018-01-25
          相关资源
          最近更新 更多