What is the fastest way to insert values from datagridview to mysql database

前端 未结 3 1818
闹比i
闹比i 2021-01-16 23:51

I have a vb.net system and I want to insert 10,000 or more records from datagridview to mysql database. But it takes 8mins for 10,000 records when i tried this



        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-17 00:06

    I can't tell how much faster this will be, however there are simple optimizations to your query

    Dim queryInsert As String = "INSERT INTO tbl_shipdetails (ship_date, " & _
                                 "item_type, item_code, imei1, imei2)" & _
                                 "VALUES(@p1,'@p2,@p3,@p4,@p5)"
    Dim cmd = New  MySqlCommand(queryInsert, Myconnect)
    cmd.Parameters.Add("@p1", MySqlDbType.VarChar)
    cmd.Parameters.Add("@p2", MySqlDbType.VarChar)    
    cmd.Parameters.Add("@p3", MySqlDbType.VarChar)    
    cmd.Parameters.Add("@p4", MySqlDbType.VarChar)    
    cmd.Parameters.Add("@p5", MySqlDbType.VarChar)
    For i As Integer = 0 To DataGridView1.Rows.Count - 1
        cmd.Parameters("@p1").Value = DataGridView1.Rows(i).Cells(1).Value
        cmd.Parameters("@p2").Value = DataGridView1.Rows(i).Cells(2).Value 
        cmd.Parameters("@p3").Value = DataGridView1.Rows(i).Cells(3).Value
        cmd.Parameters("@p4").Value = DataGridView1.Rows(i).Cells(4).Value
        cmd.Parameters("@p5").Value = DataGridView1.Rows(i).Cells(5).Value
        cmd.ExecuteNonQuery()
    Next
    

    Using parameters allows you to build the MySqlCommand just one time outside the loop and avoids also the work needed to concatenate the strings. (Not to mention the problem of Sql Injection)

    Notice that I have followed your hint in the sql text where all of your fields seems to be of string(VarChar) type. If your fields are of different datatype then you should adjust the MySqlDbType enum to your correct datatype (and convert the input values=

提交回复
热议问题