工作中要频繁的处理一些数据导入,又不想手工去做,因此用了神器SqlBulkCopy。在MSDN查看了此类的帮助文档几经波折终于搞定,记录下来方便以后查阅。

MSDN实例:

 using System.Data.SqlClient;

 class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open(); // Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart); // Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader(); // Open the destination connection. In the real world you would
// not use SqlBulkCopy to move data from one table to the other
// in the same database. This is for demonstration purposes only.
using (SqlConnection destinationConnection =
new SqlConnection(connectionString))
{
destinationConnection.Open(); // Set up the bulk copy object.
// Note that the column positions in the source
// data reader match the column positions in
// the destination table so there is no need to
// map columns.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns"; try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
} // Perform a final count on the destination
// table to see how many rows were added.
long countEnd = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
} private static string GetConnectionString()
// To avoid storing the sourceConnection string in your code,
// you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
"Initial Catalog=AdventureWorks;";
}
}

MSDN 地址:https://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx

自己的测试代码:

 /// <summary>
/// 将DataTable表数据插入数据库目标表
/// DataTable Name 和数据库目标表名称一致,DataTable列名为目标数据库目标表字段
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="dbFlag">数据库标识</param>
/// <returns></returns>
public static bool MassInsert(DataTable dt, string dbFlag)
{
if (dt == null || dt.Rows.Count == )
{
Logger.Write("DataTable为空或无填充行", "大数据操作", "");
return false;
}
if (String.IsNullOrEmpty(dt.TableName))
{
Logger.Write("DataTableName为空无法确定目标数据库表", "大数据操作", "");
return false;
}
SqlConnection con = HelpGetSqlCon(dbFlag);//动态获取SqlConnection对象
DateTime time = DateTime.Now;
SqlTransaction tra = con.BeginTransaction();//事务
SqlBulkCopy sqlBC = new SqlBulkCopy(con, SqlBulkCopyOptions.Default, tra);
try
{
sqlBC.DestinationTableName = dt.TableName;
//一次批量的插入的数据量
sqlBC.BatchSize = dt.Rows.Count;
sqlBC.WriteToServer(dt);
Logger.Write("【MassInsert】[" + dt.Rows.Count + "]条数据共耗时[" + (DateTime.Now - time).TotalSeconds.ToString() + "]秒", "", ""); //记录日志
tra.Commit();
return true;
}
catch (Exception ex)
{
tra.Rollback();
Logger.WriteException("MassInsert异常", "", ex, "");
return false;
}
finally
{
dt.Clear();
dt.Dispose();
sqlBC.Close();
con.Dispose();
con.Close();
}
}

以上代码可以插入主键,如果主键重复则事务回滚

正常测试结果:

【2015-04-29 12:49:44】
【MassInsert】[182689]条数据共耗时[3.4911996]秒

主键重复测试结果:

【2015-04-29 12:41:16】

Message:MassInsert异常

Ex.Message:违反了 PRIMARY KEY 约束“PK_AUTHCODES”。不能在对象“dbo.AuthCodes”中插入重复键。重复键值为 (1)。
语句已终止。

Ex.StackTrace: 在 System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
在 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
在 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
在 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
在 System.Data.SqlClient.SqlBulkCopy.RunParser(BulkCopySimpleResultSet bulkCopyHandler)
在 System.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinuedOnSuccess(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
在 System.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinued(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
在 System.Data.SqlClient.SqlBulkCopy.CopyBatchesAsync(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
在 System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestContinuedAsync(BulkCopySimpleResultSet internalResults, CancellationToken cts, TaskCompletionSource`1 source)
在 System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestAsync(CancellationToken cts, TaskCompletionSource`1 source)
在 System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalAsync(CancellationToken ctoken)
在 System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServerAsync(Int32 columnCount, CancellationToken ctoken)
在 System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table, DataRowState rowState)
在 System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table)

批量插入数据利器之SqlBulkCopy的更多相关文章

  1. .Net批量插入数据到SQLServer数据库,System.Data.SqlClient.SqlBulkCopy类批量插入大数据到数据库

    批量的的数据导入数据库中,尽量少的访问数据库,高性能的对数据库进行存储. 采用SqlBulkCopy来处理存储数据.SqlBulkCopy存储大批量的数据非常的高效,将内存中的数据表直接的一次性的存储 ...

  2. sql 中的Bulk和C# 中的SqlBulkCopy批量插入数据 ( 回顾 and 粗谈 )

    通常,我们会对于一个文本文件数据导入到数据库中,不多说,上代码. 首先,表结构如下.   其次,在我当前D盘中有个文本文件名为2.txt的文件. 在数据库中,可以这样通过一句代码插入. Bulk in ...

  3. C# 批量插入表SQLSERVER SqlBulkCopy往数据库中批量插入数据

    #region 帮助实例:SQL 批量插入数据 多种方法 /// <summary> /// SqlBulkCopy往数据库中批量插入数据 /// </summary> /// ...

  4. SqlBulkCopy批量插入数据时,不执行触发器和约束的解决方法

    原文:SqlBulkCopy批量插入数据时,不执行触发器和约束的解决方法 在new SqlBulkCopy对象的时候,设置一下SqlBulkCopyOptions选项即可,按位或运算 SqlBulkC ...

  5. 用SqlBulkCopy批量插入数据到SqlServer数据库表中

    首先创建一个数据库连接类:SQLHelper using System; using System.Collections.Generic; using System.Linq; using Syst ...

  6. c# 数据库批量插入数据SqlBulkCopy 示例

    /// <summary> /// 批量插入数据 /// </summary> public static void SqlBulkInsert(DataTable dt, s ...

  7. MSSQL使用sqlbulkcopy批量插入数据

    具体代码如下: /// <summary> /// 批量插入数据到BayonetZipFailedPic表 /// </summary> /// <param name= ...

  8. C#:用SqlBulkCopy来实现批量插入数据

    SqlBulkCopy是.net2.0的新特性,平时用的很少,但是其功能却是非常强大,对于批量插入数据性能非常优越 代码 /// /// bulk插入/// private void BulkInse ...

  9. 使用 SqlBulkCopy 批量插入数据

    /// <summary> /// 使用SqlBulkCopy将DataTable中的数据批量插入数据库中 /// </summary> /// <param name= ...

随机推荐

  1. Dispose 与 close 方法 的区别

    Dispose : 释放 托管 与 非托管资源. Finalize : 释放 非托管资源. Close: 关闭资源后,可以再次使用资源.

  2. 利用C#查看特定服务是否安装

    需求:想通过C#代码来查看IIS服务或者MSMQ是否已经安装 分析:IIS服务和MSMQ安装完成后都会创建windows服务,所以我们只需要查看对应的服务是否存在即可. 准备工作: IIS服务名称:W ...

  3. React Native之持久化存储(AsyncStorage、react-native-storage)的使用

    AsyncStorage是一个简单的.异步的.持久化的Key-Value存储系统,它对于App来说是全局性的.这是官网上对它的介绍.可以知道,这个asyncstorage也是以键值对的形式进行存储数据 ...

  4. Linux服务器配置秘钥对连接

    [root@check2 ~]# ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to sa ...

  5. Linux下的sed命令使用详解

    sed是stream editor的简称,也就是流编辑器.它一次处理一行内容,处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”pattern space,接着用sed命令处理缓冲区中的内容, ...

  6. Git常用分支操作

    新建分支 git branch branchname 切换到分支dev git checkout branchname 查看所有的分支信息 git branch -a 查看远程分支信息 git bra ...

  7. [BZOJ1721][Usaco2006 Mar]Ski Lift 缆车支柱

    Description Farmer Ron in Colorado is building a ski resort for his cows (though budget constraints ...

  8. HDU 1337 && POJ 1218&& zju 1350 方法总结

    题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1337 杭电 http://poj.org/problem?id=1218清华 http://acm.zj ...

  9. JAVA反序列化漏洞解决办法

    一.漏洞描述: 近期,反序列化任意代码执行漏洞持续发酵,越来越多的系统被爆出存在此漏洞.Apache Commons工具集广泛应用于JAVA技术平台,存在Apache Commons Componen ...

  10. cnetos升级内核玩docker

    最近在学习docker容器.在阿里云上的服务器内核版本比较低.所以,需要先升级. 查看内核命令:uname -r 升级内核,网上也有很多种方式.一般都是下载内核包,然后自己编译.不过这种方式需要注意的 ...