SqlBulkCopy.WriteToServer has 4 overloads:
SqlBulkCopy.WriteToServer (DataRow[])
    Copies all rows from the supplied DataRow array to a destination table specified by the 
    DestinationTableName property of the SqlBulkCopy object. 
SqlBulkCopy.WriteToServer (DataTable)
    Copies all rows in the supplied DataTable to a destination table specified by the 
    DestinationTableName property of the SqlBulkCopy object. 
SqlBulkCopy.WriteToServer (IDataReader)
    Copies all rows in the supplied IDataReader to a destination table specified by the 
    DestinationTableName property of the SqlBulkCopy object. 
SqlBulkCopy.WriteToServer (DataTable, DataRowState)
    Copies only rows that match the supplied row state in the supplied DataTable to a 
    destination table specified by the DestinationTableName property of the SqlBulkCopy object.

When importing text files with this method you have to create a DataTable first, import the text file 
to the created DataTable and then write this DataTable to server.

With this we're acctually performing 2 tasks in .net:
1. Fill data from text file to DataTable in memory
2. Fill data from DataTable in memory to SQL server

Compared to SQL servers native bulk import methods where we just import the text file directly.

I used the same file and the same table structure as in previous bulk import methods described in Last
The time it took to complete the whole process was around 30 seconds.

This is the code i used for import:

private void StartImport()
{
Stopwatch sw = new Stopwatch();
sw.Start();
SqlBulkCopy bulkCopy = new SqlBulkCopy("Server=ServerName;Database=test;Trusted_Connection=True;",
SqlBulkCopyOptions.TableLock);
bulkCopy.DestinationTableName = "dbo.testSQLBulkCopy";
bulkCopy.WriteToServer(CreateDataTableFromFile());
sw.Stop();
txtResult.Text = (sw.ElapsedMilliseconds/1000.00).ToString();
}
private DataTable CreateDataTableFromFile()
{
DataTable dt = new DataTable();
DataColumn dc;
DataRow dr; dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Int32");
dc.ColumnName = "c1";
dc.Unique = false;
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Int32");
dc.ColumnName = "c2";
dc.Unique = false;
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Int32");
dc.ColumnName = "c3";
dc.Unique = false;
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Int32");
dc.ColumnName = "c4";
dc.Unique = false;
dt.Columns.Add(dc);
StreamReader sr = new StreamReader(@"d:\work\test.txt");
string input;
while ((input = sr.ReadLine()) != null)
{
string[] s = input.Split(new char[] { '|' });
dr = dt.NewRow();
dr["c1"] = s[];
dr["c2"] = s[];
dr["c3"] = s[];
dr["c4"] = s[];
dt.Rows.Add(dr);
}
sr.Close();
return dt;
}

Bulk Import Methods are ad below..:-

1. BCP
2. Bulk Insert
3. OpenRowset with BULK option
4. SQL Server Integration Services - SSIS

I ran each bulk import option 12 times, disregarded best and worst time and averaged the remaining ten times.
Results are:

1. SSIS - FastParse ON = 7322 ms
2. SSIS - FastParse OFF = 8387 ms
3. Bulk Insert = 10534 ms
4. OpenRowset = 10687 ms
5. BCP = 14922 ms

So speed gain is quite large when using FastParse.
I was also surprised that SSIS - FastParse OFF method was faster by 20% to Bulk Insert and OpenRowset
and around 40% faster than BCP.

Since my desire was to test how much faster is importing flat files when FastParse option is used
I created a text file containing 4 bigint columns with 1,000,000 rows.

The script i used to create a sample test file in C#:

string str;
StreamWriter sw = new StreamWriter(@"d:\work\test.txt");
for (int i = ; i <= ; i++)
{
str = i.ToString() + "|" + Convert.ToString(i * ) + "|" + Convert.ToString(i * ) + "|" + Convert.ToString(i / );
sw.WriteLine(str);
}
sw.Close();

I also created this format file for use with BCP, Bulk Insert and OpenRowset:

9.0
4
1 SQLBIGINT 0 8 "|" 1 c1 ""
2 SQLBIGINT 0 8 "|" 2 c2 ""
3 SQLBIGINT 0 8 "|" 3 c3 ""
4 SQLBIGINT 0 8 "\r\n" 4 c4 ""

SSIS Package was a very simple one with a Flat File source and SQL server destination objects.

The sql script i used is:

create database test
go
use test
go
-- ran for each SSIS test run
-- SSIS data type for each column was "eight-byte signed integer [DT_I8]"
drop table testFastParse
create table testFastParse(c1 bigint, c2 bigint, c3 bigint, c4 bigint)
go
-- insert data using OPENROWSET
create table testOpenRowset(c1 bigint, c2 bigint, c3 bigint, c4 bigint)
go
DBCC DROPCLEANBUFFERS
declare @start datetime
set @start = getdate()
insert into testOpenRowset(c1, c2, c3, c4)
SELECT t1.c1, t1.c2, t1.c3, t1.c4
FROM OPENROWSET( BULK 'd:\work\test.txt',
FORMATFILE = 'd:\work\testImport-f-n.Fmt') AS t1(c1, c2, c3, c4);
select getdate() - @start as ElapsedTime
drop table testOpenRowset
-- insert data using Bulk Insert
create table testBulkInsert(c1 bigint, c2 bigint, c3 bigint, c4 bigint)
go
DBCC DROPCLEANBUFFERS
declare @start datetime
set @start = getdate()
BULK INSERT testBulkInsert
FROM 'd:\work\test.txt'
WITH (FORMATFILE='d:\work\testImport-f-n.Fmt')
select getdate() - @start as ElapsedTime
drop table testBulkInsert
go
-- insert data using BCP
create table testBCP(c1 bigint, c2 bigint, c3 bigint, c4 bigint)
go
DBCC DROPCLEANBUFFERS
exec master..xp_cmdshell 'bcp test.dbo.testBCP in d:\work\test.txt -T -b1000000 -fd:\work\testImport-f-n.Fmt'
drop table testBCP
go
drop database test

C# .NET - Sql Bulk Insert from multiple delimited Textfile using c#.net的更多相关文章

  1. SQL SERVER – Import CSV File Into SQL Server Using Bulk Insert – Load Comma Delimited File Into SQL Server

    CSV stands for Comma Separated Values, sometimes also called Comma Delimited Values. Create TestTabl ...

  2. SQL Server Bulk Insert批量数据导入

    SQL Server的Bulk Insert语句可以将本地或远程的数据文件批量导入到数据库中,速度非常的快.远程文件必须共享才行,文件路径须使用通用约定(UNC)名称,即"\\服务器名或IP ...

  3. SQL Server批量数据导出导入Bulk Insert使用

    简介 Bulk insert命令区别于BCP命令之处在于它是SQL server脚本语句,它可以将本地或远程的文件数据批量导入数据库,速度非常之快:远程文件必须共享才行, 文件路径须使用通用约定(UN ...

  4. BULK INSERT如何将大量数据高效地导入SQL Server

    转载自:http://database.51cto.com/art/201108/282631.htm BULK INSERT如何将大量数据高效地导入SQL Server 本文我们详细介绍了BULK ...

  5. SQL SERVER 使用BULK Insert将txt文件中的数据批量插入表中(1)

    1/首先建立数据表 CREATE TABLE BasicMsg( RecvTime FLOAT NOT NULL , --接收时间,不存在时间相同的数据 AA INT NOT NULL, --24位地 ...

  6. Sql server bulk insert

    Bulk Insert Sql server 的bulk insert语句可以高效的导入大数据量的平面文件(txt,csv文件)到数据库的一张表中,其用法如下: bulk insert test fr ...

  7. [转]UTF-8 encoding support for the BCP utility and BULK INSERT Transact-SQL command in SQL Server 2014 SP2

    本文转自:https://support.microsoft.com/en-us/help/3136780/utf-8-encoding-support-for-the-bcp-utility-and ...

  8. Bulk Insert:将文本数据(csv和txt)导入到数据库中

    将文本数据导入到数据库中的方法有很多,将文本格式(csv和txt)导入到SQL Server中,bulk insert是最简单的实现方法 1,bulk insert命令,经过简化如下 BULK INS ...

  9. 笔记整理之 Bulk Insert

    之前2篇日志整理了BCP大致的用法,这次整理一下它的兄弟 Bulk Insert 的写法以及和bcp那边的结合的用法. 首先,Bulk Insert 语句要在连接了Sql Server 服务器之后才执 ...

随机推荐

  1. Win 10服务智能化有什么依据?

            在今年7月29日之后.Win 10操作系统就叫"视窗服务"了,当中有没有"智能'因素呢?能不能叫做"智能操作系统"呢?为什么?什么是& ...

  2. IOS使用AVAudioPlayer播放mp3歌曲文件并监听来电打断

    本实例实现了AVAudioPlayer播放mp3歌曲文件,实现了播放.暂停.继续操作,音乐音量控制.播放进度显示,同时监听来电打断事件 一.控件初始化 - (void)viewDidLoad { [s ...

  3. Vue2 原理解析

    现代主流框架均使用一种数据=>视图的方式,隐藏了繁琐的dom操作,采用了声明式编程(Declarative Programming)替代了过去的类jquery的命令式编程(Imperative ...

  4. how to build jdk 9 source code

    http://hg.openjdk.java.net/build-infra/jdk9/raw-file/tip/README-builds.html#vs2013 http://royvanrijn ...

  5. python(41):copy拷贝(深拷贝deepcopy与浅拷贝copy)

    Python中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的copy模块. 1.copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象. 2.copy.deepco ...

  6. 扩展music-list.vue让列表前三名显示🏆奖杯

    1.在music-list.vue中写DOM <li @click="seletItem(song,index)" class="song-item" v ...

  7. c++11并发机制

    传统意义上OS提供的并发机制包含进程和线程两个级别.考虑到实际复杂性,c++11仅提供了线程并发机制. c++11提供的线程并发机制主要位于四个头文件中:..... 线程并发机制包括线程管理.原子操作 ...

  8. C# 实现list=list.OrderBy(q=>q.字段名).ToList(); 按多个字段排序

    //倒序 list.OrderByDescending(i => i.a).ThenByDescending(i => i.b); //顺序 list.OrderBy(i => i. ...

  9. HTML <meta> 标签 和 http-equiv

    前言 经常在写HTML,但是对于meta 的设置却一直疏于关注. <meta> 是什么 <meta> 是一个HTML的标签(辅助性标签). 它的位置位于文档的头部  <h ...

  10. 【Java】自动类型转换规则

    自动类型转换遵循下面的规则: 若参与运算的数据类型不同,则先转换成同一类型,然后进行运算. 转换按数据长度增加的方向进行,以保证精度不降低.例如int型和long型运算时,先把int量转成long型后 ...