Insert 2 million ro...
Notifications
Clear all

Insert 2 million rows into SQL Server quickly

RSS

(@sathish)
Member Moderator
Joined: 1 year ago
Posts: 1391
20/03/2021 9:25 am

我想插入about 2 million rows from a text file.

And with inserting, I want to create some master tables.

What is the most reliable and fast way to insert such a large set of data into the SQL Server?


Quote
(@anamika)
Noble Member
Joined: 1 year ago
Posts: 1381
20/03/2021 9:26 am

You can try this method and it will significantly reduce the database insert execution time.

List<string> toinsert =newList<string>(); StringBuilder insertCmd =newStringBuilder("INSERT INTO tabblename (col1, col2, col3) VALUES ");foreach(varrowinrows) {// the point here is to keep values quoted and avoid SQL injectionvarfirst = row.First.Replace("'","''")varsecond = row.Second.Replace("'","''")varthird = row.Third.Replace("'","''") toinsert.Add(string.Format("( '{0}', '{1}', '{2}' )", first, second, third)); }if(toinsert.Count !=0) { insertCmd.Append(string.Join(",", toinsert)); insertCmd.Append(";"); }using(MySqlCommand myCmd =newMySqlCommand(insertCmd.ToString(), SQLconnectionObject)) { myCmd.CommandType = CommandType.Text; myCmd.ExecuteNonQuery(); }

*Create the SQL connection object and replace it where I have written the SQLconnectionObject.


ReplyQuote
Share:
Baidu