Asp.net code (Sqlserver) for fast data insertion)

Source: Internet
Author: User

Copy codeThe Code is as follows:
Using System. Data;
Using System. Diagnostics;
Using System. Data. SqlClient;
   
String connectionString = "Data Source = HG-J3EJJ9LSW5PY; Initial Catalog = Test; User ID = sa; password = hg ";
DataTable dataTable = SQL _. select_datagrid ("select a from large where 1 = 0"). Tables [0];
String passportKey;
For (int I = 0; I <100000; I ++)
{
PassportKey = Guid. NewGuid (). ToString ();
DataRow dataRow = dataTable. NewRow ();
DataRow [0] = passportKey;
DataTable. Rows. Add (dataRow );
}
SqlConnection sqlConnection = new SqlConnection (connectionString );
SqlConnection. Open ();
SqlTransaction sqltran = sqlConnection. BeginTransaction ();
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy (sqlConnection, SqlBulkCopyOptions. KeepIdentity, sqltran );
SqlBulkCopy. DestinationTableName = "large ";
SqlBulkCopy. BatchSize = dataTable. Rows. Count;
If (dataTable! = Null & dataTable. Rows. Count! = 0)
{
SqlBulkCopy. WriteToServer (dataTable );
}
SqlBulkCopy. Close ();
Sqltran. Rollback ();
SqlConnection. Close ();

Note: <1> sqlBulkCopy. DestinationTableName = "large"; large indicates the name of the target table.
<2> the DataTable structure must be the same as that of the table in the database.
(DataTable cannot contain more columns than those in the database)
(The able column can be smaller than the column in the database if the column in the database has the default value)
<3> here I use transactions. You can also use them without transactions.

Related Article

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.