首页 > 代码库 > C# 通过DataTable插入大量数据,50万数据只需要3秒

C# 通过DataTable插入大量数据,50万数据只需要3秒

技术分享

 

数据库sql脚本:

CREATE DATABASE TESTDB
GO
USE TESTDB
GO

CREATE TABLE TAB1
(
        NAME NVARCHAR(10),
        AGE NVARCHAR(10) ,
        ADRESS NVARCHAR(10) 
)
delete  TAB1

SELECT * FROM TAB1 
SELECT COUNT(0) FROM TAB1

 

class Program
    {
        static void Main(string[] args)
        {
            string conn = "Data Source=.;Initial Catalog=TESTDB;user id=sa;password=123456";
            DataTable dt = new DataTable();
            dt.Columns.Add("Name1");
            dt.Columns.Add("Age");
            dt.Columns.Add("Adress");
            for (int i = 0; i < 500000; i++)
            {
                dt.Rows.Add("Name" + i, i, "地址" + i);
            }
            DataTableToSQLServer(dt, conn, "TAB1");
        }

        public static void DataTableToSQLServer(DataTable dt, string connectionString, string tableName)
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            using (SqlConnection destinationConnection = new SqlConnection(connectionString))
            {
                destinationConnection.Open();
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
                {
                    try
                    {
                        bulkCopy.DestinationTableName = tableName;//要插入的表的表名
                        bulkCopy.BatchSize = dt.Rows.Count;
                        bulkCopy.ColumnMappings.Add("Name1", "NAME");//映射字段名 DataTable列名 ,数据库 对应的列名  
                        bulkCopy.ColumnMappings.Add("Age", "AGE");
                        bulkCopy.ColumnMappings.Add("Adress", "ADRESS");
                        bulkCopy.WriteToServer(dt);
                        Console.WriteLine("插入成功!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (destinationConnection.State == ConnectionState.Open)
                        {
                            destinationConnection.Close();
                        }
                        stopwatch.Stop();
                        Console.WriteLine("插入:" + dt.Rows.Count + "数据,耗时" + (stopwatch.ElapsedMilliseconds / 1000).ToString() + "");
                    }
                }
            }
        }
    }

 

C# 通过DataTable插入大量数据,50万数据只需要3秒