C # efficient SQL Server Import using excel

Source: Internet
Author: User

In SQL Server, many people concatenate SQL statements by repeating the excel data read by oledb. This is not only error-prone but also inefficient. The best way is to use bcp, that is, System. data. sqlClient. sqlBulkCopy class. Not only is the speed fast, but the code is simple. The following test code imports a sheet with more than 60 thousand pieces of data, including reading (all reading is slow). It takes about 10 seconds in my development environment, the real import process takes only 4.5 seconds.

 


Using System;
Using System. Data;
Using System. Windows. Forms;
Using System. Data. OleDb;
Namespace WindowsApplication2
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}

Private void button#click (object sender, EventArgs e)
{
// Test. Import Sheet 1 in excel to sqlserver.
String connString = "server = localhost; uid = sa; pwd = sqlgis; database = master ";
System. Windows. Forms. OpenFileDialog fd = new OpenFileDialog ();
If (fd. ShowDialog () = DialogResult. OK)
{
TransferData (fd. FileName, "sheet1", connString );
}
}

Public void TransferData (string excelFile, string sheetName, string connectionString)
{
DataSet ds = new DataSet ();
Try
{
// Obtain all data
String strConn = "Provider = Microsoft. Jet. OLEDB.4.0;" + "Data Source =" + excelFile + ";" + "Extended Properties = Excel 8.0 ;";
OleDbConnection conn = new OleDbConnection (strConn );
Conn. Open ();
String strExcel = "";
OleDbDataAdapter myCommand = null;
StrExcel = string. Format ("select * from [{0} $]", sheetName );
MyCommand = new OleDbDataAdapter (strExcel, strConn );
MyCommand. Fill (ds, sheetName );

// Create a table if the target table does not exist
String strSql = string. Format ("if object_id ({0}) is null create table {0} (", sheetName );
Foreach (System. Data. DataColumn c in ds. Tables [0]. Columns)
{
StrSql + = string. Format ("[{0}] varchar (255),", c. ColumnName );
}
StrSql = strSql. Trim (,) + ")";

Using (System. Data. SqlClient. SqlConnection sqlconn = new System. Data. SqlClient. SqlConnection (connectionString ))
{
Sqlconn. Open ();
System. Data. SqlClient. SqlCommand command = sqlconn. CreateCommand ();
Command. CommandText = strSql;
Command. ExecuteNonQuery ();
Sqlconn. Close ();
}
// Use bcp to import data
Using (System. Data. SqlClient. SqlBulkCopy bcp = new System. Data. SqlClient. SqlBulkCopy (connectionString ))
{
Bcp. SqlRowsCopied + = new System. Data. SqlClient. SqlRowsCopiedEventHandler (bcp_SqlRowsCopied );
Bcp. BatchSize = 100; // number of rows transmitted each time
Bcp. policyafter = 100; // number of rows prompted by the progress
Bcp. DestinationTableName = sheetName; // target table
Bcp. WriteToServer (ds. Tables [0]);
}
}
Catch (Exception ex)
{
System. Windows. Forms. MessageBox. Show (ex. Message );
}

}

// Progress display
Void bcp_SqlRowsCopied (object sender, System. Data. SqlClient. SqlRowsCopiedEvent

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.