按這個來算,我們那個發水票的時間就會由 10分鐘-->20秒,這可太神奇了。
於是乎,下demo,測試,改成自己一般使用的方法測試,NND,還真可以說是極速。
在此貼上我的Demo:SqlBulkCopy.rar
複製代碼 代碼如下:using System;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
namespace ConsoleAppInsertTest
{
class Program
{
static int count = 1000000; //插入的條數
static void Main(string[] args)
{
long sqlBulkCopyInsertRunTime = SqlBulkCopyInsert();
Console.WriteLine(string.Format("使用SqlBulkCopy插入{1}條資料所用的時間是{0}毫秒", sqlBulkCopyInsertRunTime, count));
long commonInsertRunTime = CommonInsert();
Console.WriteLine(string.Format("普通方式插入{1}條資料所用的時間是{0}毫秒", commonInsertRunTime, count));
Console.ReadKey();
}
/// <summary>
/// 使用普通插入資料
/// </summary>
/// <returns></returns>
private static long CommonInsert()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < count; i++)
{
SqlHelper.ExecuteNonQuery(SqlHelper.SqlConnection, CommandType.Text, "insert into passport(PassportKey) values('" + Guid.NewGuid() + "')");
}
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
/// <summary>
/// 使用SqlBulkCopy方式插入資料
/// </summary>
/// <returns></returns>
private static long SqlBulkCopyInsert()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
DataTable dataTable = GetTableSchema();
for (int i = 0; i < count; i++)
{
DataRow dataRow = dataTable.NewRow();
dataRow[2] = Guid.NewGuid();
dataTable.Rows.Add(dataRow);
}
//Console.WriteLine(stopwatch.ElapsedMilliseconds);//初始化資料時間
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(SqlHelper.SqlConnection);
sqlBulkCopy.DestinationTableName = "Passport";
if (dataTable != null && dataTable.Rows.Count != 0)
{
sqlBulkCopy.WriteToServer(dataTable);
}
sqlBulkCopy.Close();
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
private static DataTable GetTableSchema()
{
return SqlHelper.ExecuteDataset(SqlHelper.SqlConnection, CommandType.Text, "select * from Passport where 1=2").Tables[0];
}
}
}
轉自cnblogs的文章 SQL批量插入資料幾種方案的效能詳細對比