bulk方法主要思想是通过在客户端把数据都缓存在Table中,然后利用SqlBulkCopy一次性把Table中的数据插入到数据库
代码如下:
public
static
void
BulkToDB(DataTable dt)
{
SqlConnection sqlConn =
new
SqlConnection( ConfigurationManager.ConnectionStrings[
"ConnStr"
].ConnectionString); <br> SqlBulkCopy bulkCopy =
new
SqlBulkCopy(sqlConn); <br> bulkCopy.DestinationTableName =
"BulkTestTable"
; <br> bulkCopy.BatchSize = dt.Rows.Count; <br>
try
{ <br> sqlConn.Open(); <br>
if
(dt !=
null
&& dt.Rows.Count != 0) bulkCopy.WriteToServer(dt); <br> } <br>
catch
(Exception ex) <br> { <br>
throw
ex; <br> }
finally
<br> { <br> sqlConn.Close(); <br>
if
(bulkCopy !=
null
) bulkCopy.Close(); <br> } <br>} <br>
public
static
DataTable GetTableSchema() <br>{ <br> DataTable dt =
new
DataTable(); <br> dt.Columns.AddRange(
new
DataColumn[]<br> {
new
DataColumn(
"Id"
,
typeof
(
int
)),
new
DataColumn(
"UserName"
,
typeof
(
string
)),
new
DataColumn(
"Pwd"
,
typeof
(
string
))}<br> ); <br>
return
dt; <br>} <br>
static
void
Main(
string
[] args) <br>{ <br> Stopwatch sw =
new
Stopwatch(); <br>
for
(
int
multiply = 0; multiply < 10; multiply++) <br> { <br> DataTable dt = Bulk.GetTableSchema(); <br>
for
(
int
count = multiply * 100000; count < (multiply + 1) * 100000; count++) <br> { <br> DataRow r = dt.NewRow(); <br> r[0] = count; <br> r[1] =
string
.Format(
"User-{0}"
, count * multiply); <br> r[2] =
string
.Format(
"Pwd-{0}"
, count * multiply);<br> dt.Rows.Add(r); <br> }<br> sw.Start(); <br> Bulk.BulkToDB(dt); <br> sw.Stop(); <br> Console.WriteLine(
string
.Format(
"Elapsed Time is {0} Milliseconds"
, sw.ElapsedMilliseconds)); <br> } <br> Console.ReadLine(); <br>}
|
分类:
SQL
本文转自左正博客园博客,原文链接:http://www.cnblogs.com/soundcode/archive/2012/09/18/2690132.html
,如需转载请自行联系原作者