最近要做.net關於sql大量插入,找到了sqlbulkcopy(自己google下,應該很多說明了)這個好東西,於是測試下性能,用了三個方法對比:
1)直接用ado.net,for循環N次進行單條插入
2)把N條插入語句拼在一個sql,進行插入
3)直接使用sqlbulkcopy進行插入
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace SQLTEST
{
class Program
{
static void Main(string[] args)
{
//int time = 200;
test(20);
test(200);
test(2000);
test(10000);
test(50000);
Console.ReadLine();
}
public static void test(int time){
Stopwatch sp = new Stopwatch();
Console.WriteLine(time + "條數據插入測試");
//測試方法1
{
using (SqlConnection sqlcon = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=??"))
{
sqlcon.Open();
string singesql = "INSERT INTO [student] ([name],[age])VALUES('abc',3);";
SqlCommand sqlcommand = new SqlCommand(singesql, sqlcon);
//計時開始
sp.Restart();
for (int i = 0; i < time; i++)
{
sqlcommand.ExecuteNonQuery();
}
sp.Stop();
}
}
Console.WriteLine("方法1:" + sp.ElapsedMilliseconds + "毫秒");
//測試方法2
{
using (SqlConnection sqlcon = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=??"))
{
sqlcon.Open();
string singesql = "INSERT INTO [student] ([name],[age])VALUES('abc',3);";
string execsql = "";
for (int i = 0; i < time; i++)
{
execsql = execsql + singesql;
}
SqlCommand sqlcommand = new SqlCommand(execsql, sqlcon);
//計時開始
sp.Restart();
sqlcommand.ExecuteNonQuery();
sp.Stop();
}
}
Console.WriteLine("方法2:" + sp.ElapsedMilliseconds + "毫秒");
//測試方法3
{
using (SqlConnection sqlcon = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=??"))
{
sqlcon.Open();
SqlBulkCopy sqlc = new SqlBulkCopy(sqlcon);
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("age");
for (int i = 0; i < time; i++)
{
dt.Rows.Add(38009, "nemw", 123);
}
sqlc.DestinationTableName = "student";
//計時開始
sp.Restart();
sqlc.WriteToServer(dt);
sp.Stop();
}
}
Console.WriteLine("方法3:" + sp.ElapsedMilliseconds + "毫秒");
Console.WriteLine();
}
}
}
插入N條數據的測試結果如下:

效率相差還是很誇張的,大家大量數據插入還是有sqlbulkcopy吧,原理還的高手告知~~
