0

currently i have 16k rows of data in an array, i am using a for loop to loop through the data and excute an INSERT statement. In other words, each loop executes an "INSERT" statement in mysql. This is done 16000 times. This take a long time.

is there a better way to inset bulk data?.

Krimson
  • 7,386
  • 11
  • 60
  • 97

3 Answers3

0

You can try this as per post by Pascal MARTIN:

insert into your_table (field1, field2, field3)
values 
  (value1_1, value1_2, value1_3), 
  (value2_1, value2_2, value2_3), 
  (value3_1, value3_2, value3_3)
Community
  • 1
  • 1
Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
0

I accomplished this in SQL using this code (with sqlParameters):

    Dim Command As New SqlCommand(_
            "insert into hilmarc_cem_items " & _
            "(CEMID, " & _
            "ItemCode, " & _
            "UnitPrice, " & _
            "Quantity, " & _
            "UOM) "     


    Dim ItemCodes() As String = Request.Form.GetValues("ItemCode")
    Dim UnitPrices() As String = Request.Form.GetValues("UnitPrice")
    Dim Quantities() As String = Request.Form.GetValues("Quantity")
    Dim UOMs() As String = Request.Form.GetValues("UOM")

    For Counter = 0 To ItemCodes.Length - 1
        Command.CommandText &= "select @CEMID, @ItemCode" & Counter & ", @UnitPrice" & Counter & ", @Quantity" & Counter & ", @UOM" & Counter & " "
        Command.Parameters.Add("@ItemCode" & Counter, Data.SqlDbType.NVarChar).Value = ItemCodes(Counter)
        Command.Parameters.Add("@Quantity" & Counter, Data.SqlDbType.Decimal).Value = Quantities(Counter)
        Command.Parameters.Add("@UOM" & Counter, Data.SqlDbType.NVarChar).Value = UOMs(Counter)
        Command.Parameters.Add("@UnitPrice" & Counter, Data.SqlDbType.Decimal).Value = UnitPrices(Counter)
        If Not Counter = ItemCodes.Length - 1 Then
            Command.CommandText &= "union all "
        Else
            Command.CommandText &= ";"
        End If
    Next

The idea is to have a single query, get all data from array and add them in sqlCommand as parameters. The query would be like this:

    insert into myTable 
        (CEMID, 
        ItemCode,
        UnitPrice,
        Quantity, 
        UOM) 
    select @CEMID, @ItemCode0, @UnitPrice0, @Quantity0, @UOM0
    union all
    select @CEMID, @ItemCode1, @UnitPrice1, @Quantity1, @UOM1
    union all
    select @CEMID, @ItemCode1, @UnitPrice1, @Quantity1, @UOM1
    union all

I'm not sure if this is valid in MySQL, just convert to code to MySQL.

kazinix
  • 28,987
  • 33
  • 107
  • 157
0

Try to generate bulk-INSERTs statements. The length of the statement should be less then max_allowed_packet which is the maximum size of one packet or any generated/intermediate string.

If it is possible - temporarily disable or remove indexes in the table.

Devart
  • 119,203
  • 23
  • 166
  • 186