sql - How to do faster insert query in c#? -
i insert id's in sql table. following way works take long. best or better way increase speed.
using (sqlconnection connection = new sqlconnection(configurationmanager.connectionstrings["defaultconnection"].connectionstring)) { string query = ""; foreach (var id in ids) // count = 60000 { { query += "insert [table] (id) values (" + id + ");"; } } sqlcommand command = new sqlcommand(query, connection); connection.open(); using (sqldatareader reader = command.executereader()) { reader.close(); } connection.close(); }
you can use sqlbulkcopy
insert large amounts of data - this:
// define datatable columns of target table datatable tbltoinsert = new datatable(); tbltoinsert.columns.add(new datacolumn("somevalue", typeof (int))); // insert data datatable (int index = 0; index < 60000; index++) { datarow row = tbltoinsert.newrow(); row["somevalue"] = index; tbltoinsert.rows.add(row); } // set sql connection using (sqlconnection connection = new sqlconnection(configurationmanager.connectionstrings["defaultconnection"].connectionstring)) { // define sqlbulkcopy sqlbulkcopy bulkcopy = new sqlbulkcopy(connection); // give name of destination table must exist! bulkcopy.destinationtablename = "bulktesttable"; // measure time needed stopwatch sw = new stopwatch(); sw.start(); // open connection, bulk insert, close connection connection.open(); bulkcopy.writetoserver(tbltoinsert); connection.close(); // stop time measurement sw.stop(); long milliseconds = sw.elapsedmilliseconds; }
on system (pc, 32gb ram, sql server 2014) 60'000 rows inserted in 135 - 185 milliseconds.
Comments
Post a Comment