In the program, there are two ways to insert data in batches.
1, with a For loop, a piece of the insertion, measured, this way is too slow (insert 10,000 data at least 6-7 seconds), because each insert to open the database connection, execute SQL, close the connection, obviously this method is not feasible.
2. Using SqlBulkCopy, define a DataTable in the program, store the data that needs to be inserted in a DataTable, and note that the columns in the DataTable need to be consistent with the database, even if the self-increment field has corresponding columns in the DataTable.
The specific code is as follows:
DataTable dt = new DataTable (); Dt. Columns.Add ("ID", typeof (int)); Dt. Columns.Add ("Name", typeof (String)); Dt. Columns.Add ("Password", Type.GetType ("System.String")); Dt. Columns.Add ("Addtime", typeof (DateTime)); Stopwatch SW = new Stopwatch (); Sw. Start (); for (int i = 0; i < 10000; i++) {//sqlhelper.executenonquery (Sqlhelper.connstr, CommandType. Text, "INSERT into T_user (Name, Password, Addtime) VALUES (' QQ ' + i +" ', ' ww ' + i + "', GETDATE ())"); Dt. Rows.Add (NULL, "QQ" + I, "ww" + I, DateTime.Now); } using (SqlConnection conn = new SqlConnection (sqlhelper.connstr)) {SqlBulkCopy bul Kcopy = new SqlBulkCopy (conn); Bulkcopy.destinationtablename = "T_user"; bulkcopy.batchsize = dt. Rows.Count; Conn. Open (); if (dt! = null && dt. Rows.Count! = 0) {bulkcopy.writetoserver (dt); }} SW. Stop (); TimeSpan ts = sw. Elapsed; Console.WriteLine (TS. TotalMilliseconds); Console.readkey ();
After testing, it only takes hundreds of milliseconds to insert 10,000 data in this way.
C # Bulk inserting data into a database