Sql Server海量数据插入
目录
1.前言
2.BULK INSERT
3.简单示例
前言
由于昨天接到一个客户反馈导出数据卡死的问题,于是决定今天模拟一下千万级的数据,然后傻傻的等待插入数据了半天......
对于海量数据,上百万上千万的数据插入,我们用ADO.NET提供的普通一条一条数据插入非常非常慢,好在Sql Server为我们提供了批量插入方法。
BULK INSERT
语法

主要参数说明
database_name
指定的表或视图所在的数据库的名称,如果未指定,则默认为当前数据库。
schema_name
表或视图架构的名称。
table_name
要将数据大容量导入其中的表或视图的名称。
‘data_file’
数据文件的完整路径,该数据文件包含到导入到指定表或视图中的数据。使用BULK INSERT可以从磁盘导入数据。
BATCHSIZE=batch_size
指定批量处理中的行数。每个批处理作为一个事物复制到服务器。
CHECK_CONSTRAINTS
指定在大容量导入操作期间,必须检查所有对目标表或视图的约束。
FIELDTERMINATOR ='field_terminator'
指定要用于 char 和 widechar 数据文件的字段终止符,即字段的分隔符。 默认的字段终止符是 \t(制表符)。
ROWTERMINATOR ='row_terminator'
指定要用于 char 和 widechar 数据文件的行终止符,即行的分隔符。
更多参数说明,请参考: https://msdn.microsoft.com/zh-cn/library/ms188365.aspx
简单示例
为了对比BULK INSERT和普通逐条插入的差异,我们通过一个简单的示例,通过实际运行来查看效果。
第一步:在数据库新建两张一样的表,分表为Student和Student1,表结构完全相同,只有ID,NAME,AGE三个简单的字段。

第二步:新建一个控制台程序,通过一个简单的循环,生成500000条数据写入到txt文件中,关键代码如下:
/// <summary>
/// 生成测试数据
/// </summary>
private static void GenerateTestData()
{
string fileName = "sql"; int i = ;
while (i <= )
{
string strInsert = string.Format("{0},'test{0}',{0}|", i);
File.AppendText(strInsert, fileName);
i++;
}
}
第三步:封装出两个方法,分别用来执行批量插入和普通插入,具体代码如下:
/// <summary>
/// 批量插入测试
/// </summary>
private static void BulkInsertTest()
{
string strFilePath = @"D:\学习\ASP.NET\QYH.BlukInsertTest\sql.txt";
string strTableName = "Student"; /* 每一个字段的信息以“,”分割
*每一条数据以“|”符号分隔
* 每10万条数据一个事务*/
string sql = string.Format("BULK INSERT {0} FROM '{1}' WITH (FIELDTERMINATOR = ',',ROWTERMINATOR ='|',BATCHSIZE = 50000)", strTableName, strFilePath);
DBHelper dbHelper = new DBHelper();
dbHelper.Excute(sql); } /// <summary>
/// 普通插入测试
/// </summary>
private static void CommonInsertTest()
{
int i = ;
while (i <= )
{
string sqlInsert = string.Format("insert into Student1(id,Name,Age) values({0},'test{0}',{0})", i);
new DBHelper().Excute(sqlInsert);
i++;
}
}
第四步:Main主函数中调用批量插入和普通插入方法,并通过Stopwatch计算出执行时间,Pragram完整代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QYH.BlukInsertTest.FileMange;
using QYH.BlukInsertTest.DataBase;
using System.Diagnostics; namespace QYH.BlukInsertTest
{
class Program
{
static void Main(string[] args)
{
//用于生成海量数据
//GenerateTestData(); Stopwatch stopwatch = Stopwatch.StartNew();
try
{
BulkInsertTest();
}
catch (Exception)
{ //throw;
} stopwatch.Stop();
string strResult = "批量插入耗时:" + stopwatch.ElapsedMilliseconds.ToString(); Stopwatch stopwatch1 = Stopwatch.StartNew();
CommonInsertTest();
stopwatch1.Stop();
string str1Result = "普通插入耗时:" + stopwatch1.ElapsedMilliseconds.ToString(); string strTestResult = "result";
File.WriteTextAsync(strResult + "\r\n" + str1Result, strTestResult); //Console.Read();
} /// <summary>
/// 批量插入测试
/// </summary>
private static void BulkInsertTest()
{
string strFilePath = @"D:\学习\ASP.NET\QYH.BlukInsertTest\sql.txt";
string strTableName = "Student"; /* 每一个字段的信息以“,”分割
*每一条数据以“|”符号分隔
* 每10万条数据一个事务*/
string sql = string.Format("BULK INSERT {0} FROM '{1}' WITH (FIELDTERMINATOR = ',',ROWTERMINATOR ='|',BATCHSIZE = 50000)", strTableName, strFilePath);
DBHelper dbHelper = new DBHelper();
dbHelper.Excute(sql); } /// <summary>
/// 普通插入测试
/// </summary>
private static void CommonInsertTest()
{
int i = ;
while (i <= )
{
string sqlInsert = string.Format("insert into Student1(id,Name,Age) values({0},'test{0}',{0})", i);
new DBHelper().Excute(sqlInsert);
i++;
}
} /// <summary>
/// 生成测试数据
/// </summary>
private static void GenerateTestData()
{
string fileName = "sql"; int i = ;
while (i <= )
{
string strInsert = string.Format("{0},'test{0}',{0}|", i);
File.AppendText(strInsert, fileName);
i++;
}
}
}
}
示例中还用到两个辅助类,DBHelper.cs和File.cs,由于仅用于演示,所以写的非常简单,其中文件路径是写死的,可以替换成实际路径。
DBHelper.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace QYH.BlukInsertTest.DataBase
{
public class DBHelper
{
public string connectionString = "Server=.;Database=QYHDB;User ID=sa;Password=123456;Trusted_Connection=False;"; public void Excute(string sql)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandTimeout = ;
command.Connection = conn;
command.CommandText = sql;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
}
}
File.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace QYH.BlukInsertTest.FileMange
{
public class File
{
public static string strFilePath = @"D:\学习\ASP.NET\QYH.BlukInsertTest"; public static async void WriteTextAsync(string text, string fileName)
{
using (StreamWriter outputFile = new StreamWriter(strFilePath + @"\" + fileName + ".txt"))
{
await outputFile.WriteAsync(text);
}
} public static void AppendText(string text, string fileName)
{
// Append text to an existing file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(strFilePath + @"\" + fileName + ".txt",true))
{
outputFile.WriteLine(text);
}
}
}
}
一切准备就绪,开始运行,结果如下:

其中单位为毫秒,从结果我们可以看出BULK INSER插入500000条数据还不需要3秒,而普通逐条插入却需要20多分钟。
Sql Server海量数据插入的更多相关文章
- SQL Server 批量插入数据的两种方法
在SQL Server 中插入一条数据使用Insert语句,但是如果想要批量插入一堆数据的话,循环使用Insert不仅效率低,而且会导致SQL一系统性能问题.下面介绍 SQL Server支持的两种批 ...
- SQL Server 批量插入数据的两种方法(转)
此文原创自CSDN TJVictor专栏:http://blog.csdn.net/tjvictor/archive/2009/07/18/4360030.aspx 在SQL Server 中插入一条 ...
- 转:SQL Server 批量插入数据的两种方法
在SQL Server 中插入一条数据使用Insert语句,但是如果想要批量插入一堆数据的话,循环使用Insert不仅效率低,而且会导致SQL一系统性能问题.下面介绍SQL Server支持的两种批量 ...
- ASP.NET MVC与Sql Server交互, 插入数据
在"ASP.NET MVC与Sql Server建立连接"中,与Sql Server建立了连接.本篇实践向Sql Server中插入数据. 在数据库帮助类中增加插入数据的方法. p ...
- sql server不要插入大数据,开销太大
sql server或者说关系型数据库中不要做一个字段存储大数据量的设计,比如要插入3000w条数据,然后每条数据中有一个文章字段,这个字段每条大概都需要存储几m的数据,那么算下来这个表就得有几百个G ...
- SQL Server返回插入数据的ID和受影响的行数
首先看看数据库里面的数据(S_Id为自增长标识列): sql server 中返回上一次插入数据的ID(标识值)有三种方式: 第一种 @@IDENTITY: insert into Student(S ...
- SQL Server 批量插入数据方案 SqlBulkCopy 的简单封装,让批量插入更方便
一.Sql Server插入方案介绍 关于 SqlServer 批量插入的方式,有三种比较常用的插入方式,Insert.BatchInsert.SqlBulkCopy,下面我们对比以下三种方案的速度 ...
- identity in sql server 批量插入history
https://stackoverflow.com/questions/1920558/what-is-the-difference-between-scope-identity-identity-i ...
- 连接sql server、插入数据、从数据库获取时间(C#)
using System; using System.Data.SqlClient; namespace Test { //连接数据库 public class Connection { privat ...
随机推荐
- mysql时间段内查询
今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ...
- Web负载均衡的几种实现方式
Web负载均衡的几种实现方式摘要:负载均衡(Load Balance)是集群技术(Cluster)的一种应用.负载均衡可以将工作任务分摊到多个处理单元,从而提高并发处理能力.目前最常见的负载均衡应用是 ...
- 关于EF的一个简单Demo
今天使用EF的时候很奇怪的问题,添加属性后,使用程序包管理器控制台的NuGet命令更新无效,于是做了这个测试,一次性写好,自动更新,看看效果 1.首先建立一个MVC项目 2.我们选择Intern ...
- 安卓更新sdk的代理
mirrors.neusoft.edu.cn80
- EventBus 一
一.概述 EventBus是一款针对Android优化的发布/订阅事件总线.主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间 ...
- QA is more than Testing
前话:在测试这个行业做了挺多年了,都快忘记自己大学的专业是国际经济与贸易,一个选择可能就决定了一生的方向. 但既然做了选择,就走下去. ----------------- 在这么多年的工作中,测试始终 ...
- Java上传截断漏洞的解决方案
文件上传漏洞解决方案 1. 最有效的,将文件上传目录直接设置为不可执行,对于Linux而言,撤销其目录的'x'权限:实际中很多大型网站的上传应用都会放置在独立的存储上作为静态文件处理,一是方便使用缓存 ...
- Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
- Qt Visual Studio Add-in 导出的 .pri 怎么用?
今天咱们介绍一下 Qt Add-in 导出的 pri 文件怎么用. 一般需要导出这个文件, 主要应该是跨平台编译的需求, 所以这个文件里包含的东西会比较少, 咱们看下导出的文件是什么样子的: # ...
- 阿里云分布式关系数据库DRDS笔记
1.Join左边的表查询数据越少,性能越好 2.广播表作为Join的驱动表 3.SQL的Limit优化 SELECT * FROM t_order o WHERE o.id IN ( SELECT i ...