C # Bulk inserting data into a database

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.