c#批量插入

2021-06-08 17:03

阅读:602

标签:oid   格式   open()   get   error   using   批量   ram   form   

一、创建一个用来测试的数据库和表

  

 1 USE [Test]
 2 GO
 3 /****** Object:  Table [dbo].[student]    Script Date: 2019/4/11 15:38:59 ******/
 4 SET ANSI_NULLS ON
 5 GO
 6 SET QUOTED_IDENTIFIER ON
 7 GO
 8 CREATE TABLE [dbo].[student](
 9     [id] [int] IDENTITY(1,1) NOT NULL,
10     [name] [nvarchar](50) NULL,
11     [age] [int] NULL,
12     [createDate] [datetime] NULL,
13  CONSTRAINT [PK_student] PRIMARY KEY CLUSTERED 
14 (
15     [id] ASC
16 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
17 ) ON [PRIMARY]
18 
19 GO

 

方式1:一条一条插入,性能最差  

1 INSERT INTO student(name,age,createDate) VALUES(苏拉自摸1,1,2018-4-11);
2 INSERT INTO student(name,age,createDate) VALUES(苏拉自摸2,2,2018-4-11);
 1         public void InsertOne()
 2         {
 3             Console.WriteLine("采用一条一条插入的方式实现");
 4             Stopwatch sw = new Stopwatch();
 5 
 6             using (SqlConnection conn = new SqlConnection(Conn)) //using中会自动Open和Close 连接。
 7             {
 8                 string sql = "INSERT INTO student(name,age,createDate) VALUES(@a,@p,@d)";
 9                 conn.Open();
10                 for (int i = 0; i 1000000; i++)
11                 {
12                     using (SqlCommand cmd = new SqlCommand(sql, conn))
13                     {
14                         cmd.Parameters.AddWithValue("@a", "花拉子模" + i);
15                         cmd.Parameters.AddWithValue("@p", i);
16                         cmd.Parameters.AddWithValue("@d", DateTime.Now);
17                         sw.Start();
18                         cmd.ExecuteNonQuery();
19                         Console.WriteLine(string.Format("插入{0}条记录,已耗时{1}毫秒",i, sw.ElapsedMilliseconds));
20                     }
21                     if (i == 1000)
22                     {
23                         sw.Stop();
24                         break;
25                     }
26                 }
27             }
28             Console.WriteLine(string.Format("插入{0}条记录,每{4}条的插入时间是{1}毫秒,预估总得插入时间是{2}毫秒,{3}分钟",
29  1000000, sw.ElapsedMilliseconds, ((sw.ElapsedMilliseconds / 1000) * 1000000), GetMinute((sw.ElapsedMilliseconds / 1000 * 1000000)), 1000));
30         }

  运行结果:

  技术图片

  100w条记录,插完要俩小时了

方式2:使用sqlBulk

  语法如下: 

 1  BULK INSERT [ [ database_name.][ owner ].]{ table_name FROM data_file }       
 2     WITH  (   
 3             [ BATCHSIZE [ = batch_size ] ],       
 4             [ CHECK_CONSTRAINTS ],           
 5             [ CODEPAGE [ = ACP | OEM | RAW | code_page ] ],   
 6             [ DATAFILETYPE [ = char | native| widechar | widenative ] ],               
 7             [ FIELDTERMINATOR [ = field_terminator ] ],   
 8             [ FIRSTROW [ = first_row ] ],   
 9             [ FIRE_TRIGGERS ],   
10             [ FORMATFILE = format_file_path ],   
11             [ KEEPIDENTITY ],   
12             [ KEEPNULLS ],   
13             [ KILOBYTES_PER_BATCH [ = kilobytes_per_batch ] ],      
14             [ LASTROW [ = last_row ] ],   
15             [ MAXERRORS [ = max_errors ] ],   
16             [ ORDER ( { column [ ASC | DESC ] } [ ,...n ] ) ],     
17             [ ROWS_PER_BATCH [ = rows_per_batch ] ],   
18             [ ROWTERMINATOR [ = row_terminator ] ],             
19             [ TABLOCK ],   
20     )  

  相关参数说明:  

 1 BULK INSERT    
 2    [ database_name . [ schema_name ] . | schema_name . ] [ table_name | view_name ]    
 3       FROM data_file    
 4      [ WITH    
 5         (    
 6    [ [ , ] BATCHSIZE = batch_size ]    --BATCHSIZE指令来设置在单个事务中可以插入到表中的记录的数量   
 7    [ [ , ] CHECK_CONSTRAINTS ]     --指定在大容量导入操作期间,必须检查所有对目标表或视图的约束。若没有 CHECK_CONSTRAINTS 选项,则所有 CHECK 和 FOREIGN KEY 约束都将被忽略,并且在此操作之后表的约束将标记为不可信。   
 8    [ [ , ] CODEPAGE = { ACP | OEM | RAW | code_page } ]  --指定该数据文件中数据的代码页   
 9    [ [ , ] DATAFILETYPE =    
10       { char | native| widechar | widenative } ]  --指定 BULK INSERT 使用指定的数据文件类型值执行导入操作。   
11    [ [ , ] FIELDTERMINATOR = field_terminator ]  --标识分隔内容的符号   
12    [ [ , ] FIRSTROW = first_row ]    --指定要加载的第一行的行号。默认值是指定数据文件中的第一行   
13    [ [ , ] FIRE_TRIGGERS ]     --是否启动触发器   
14    [ [ , ] FORMATFILE = format_file_path ]    
15    [ [ , ] KEEPIDENTITY ]   --指定导入数据文件中的标识值用于标识列   
16    [ [ , ] KEEPNULLS ]    --指定在大容量导入操作期间空列应保留一个空值,而不插入用于列的任何默认值   
17    [ [ , ] KILOBYTES_PER_BATCH = kilobytes_per_batch ]    
18    [ [ , ] LASTROW = last_row ]   --指定要加载的最后一行的行号   
19    [ [ , ] MAXERRORS = max_errors ]   --指定允许在数据中出现的最多语法错误数,超过该数量后将取消大容量导入操作。   
20    [ [ , ] ORDER ( { column [ ASC | DESC ] } [ ,...n ] ) ]  --指定数据文件中的数据如何排序   
21    [ [ , ] ROWS_PER_BATCH = rows_per_batch ]    
22    [ [ , ] ROWTERMINATOR = row_terminator ]   --标识分隔行的符号   
23    [ [ , ] TABLOCK ]     --指定为大容量导入操作持续时间获取一个表级锁   
24    [ [ , ] ERRORFILE = file_name ]   --指定用于收集格式有误且不能转换为 OLE DB 行集的行的文件。   
25         )]   

  代码:

  

 1 public void InsertTwo()
 2         {
 3             Console.WriteLine("使用Bulk插入的实现方式");
 4             Stopwatch sw = new Stopwatch();
 5             DataTable dt = GetTableSchema();
 6 
 7             using (SqlConnection conn = new SqlConnection(Conn))
 8             {
 9                 SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);
10                 bulkCopy.DestinationTableName = "student";
11                 bulkCopy.BatchSize = dt.Rows.Count;
12                 conn.Open();
13                 sw.Start();
14 
15                 for (int i = 0; i 1000000; i++)
16                 {
17                     DataRow dr = dt.NewRow();
18                     dr["name"] = "蔑儿乞人" + i;
19                     dr["age"] = i;
20                     dr["createDate"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
21                     dt.Rows.Add(dr);
22                 }
23                 if (dt != null && dt.Rows.Count != 0)
24                 {
25                     bulkCopy.WriteToServer(dt);
26                     sw.Stop();
27                 }
28                 Console.WriteLine(string.Format("插入{0}条记录共花费{1}毫秒,{2}分钟", 1000000, sw.ElapsedMilliseconds, GetMinute(sw.ElapsedMilliseconds)));
29             }
30         }
31         public DataTable GetTableSchema()
32         {
33             DataTable dt = new DataTable();
34             dt.Columns.AddRange(
35                 new DataColumn[] {
36         new DataColumn("name",typeof(string)),
37         new DataColumn("age",typeof(int)),
38         new DataColumn("createDate",typeof(DateTime ))});
39             return dt;
40         }

 

方式3:insert into

  

INSERT INTO Product(name,age,createDate)
 SELECT 托多11,2019-4-11, 
 UNION ALL 
 SELECT 托多22,2019-4-11, 
 UNION ALL
...... 

 

四、拼接sql

  

1 INSERT INTO student(name,age,createDate)VALUES 
2 (牛栏1段,160,‘2019-4-11‘)
3 ,(牛栏2段,260,‘2019-4-11‘)
4 ......

 

c#批量插入

标签:oid   格式   open()   get   error   using   批量   ram   form   

原文地址:https://www.cnblogs.com/hyunbar/p/10691149.html


评论


亲,登录后才可以留言!