MySql Bulk insert

Yatendra Goel picture Yatendra Goel · Apr 3, 2011 · Viewed 21.4k times · Source

I want to insert some 4K rows in the MySql db. I don't want to fire 4k 'insert' queries. Is there any way by which I can fire only one insert query to store those 4k rows in the db.

I searched on internet and everywhere I found that the users are doing bulk insert into the db from a file.

In my case, I have the data in the memory and I don't want to first write that data to a file to do bulk insert. If I do that then I will add delay in the program.

Answer

Pascal MARTIN picture Pascal MARTIN · Apr 3, 2011

You could write a single insert query that would do several inserts in a single call to the database :

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)


Here, with the example I've given, this single query would have inserted three rows in the table.