SQLServer批量插⼊数据的两种⽅法
在SQL Server 中插⼊⼀条数据使⽤Inrt语句,但是如果想要批量插⼊⼀堆数据的话,循环使⽤Inrt不仅效率低,⽽且会导致SQL ⼀系统性能问题。下⾯介绍SQL Server⽀持的两种批量数据插⼊⽅法:Bulk和表值参数(Table-Valued Parameters)。
运⾏下⾯的脚本,建⽴测试数据库和表值参数。
[c-sharp]
1. --Create DataBa
2. create databa BulkTestDB;
3. go
4. u BulkTestDB;
5. go
6. --Create Table
7. Create table BulkTestTable(
8. Id int primary key,
9. UrName nvarchar(32),
10. Pwd varchar(16))
11. go
12. --Create Table Valued
13. CREATE TYPE BulkUdt AS TABLE
14. (Id int,
15. UrName nvarchar(32),
16. Pwd varchar(16))
--Create DataBa create databa BulkTestDB; go u BulkTestDB; go --Create Table Create table
BulkTestTable( Id int primary key, UrName nvarchar(32), Pwd varchar(16)) go --Create Table Valued CREATE TYPE BulkUdt AS TABLE (Id int, UrName nvarchar(32), Pwd varchar(16))
下⾯我们使⽤最简单的Inrt语句来插⼊100万条数据,代码如下:
[c-sharp]
1. Stopwatch sw = new Stopwatch();
2.
3. SqlConnection sqlConn = new SqlConnection(
4. ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);//连接数据库
5.
6. SqlCommand sqlComm = new SqlCommand();
7. sqlComm.CommandText = string.Format("inrt into BulkTestTable(Id,UrName,Pwd)values(@p0,@p1,@p2)");//参数化
SQL
8. sqlComm.Parameters.Add("@p0", SqlDbType.Int);
9. sqlComm.Parameters.Add("@p1", SqlDbType.NVarChar);
10. sqlComm.Parameters.Add("@p2", SqlDbType.VarChar);
11. sqlComm.CommandType = CommandType.Text;
12. sqlComm.Connection = sqlConn;
13. sqlConn.Open();
14. try
15. {
16. //循环插⼊100万条数据,每次插⼊10万条,插⼊10次。
17. for (int multiply = 0; multiply < 10; multiply++)
18. {
19. for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)
20. {
21.
22. sqlComm.Parameters["@p0"].Value = count;
23. sqlComm.Parameters["@p1"].Value =string.Format("Ur-{0}", count * multiply);
24. sqlComm.Parameters["@p2"].Value =string.Format("Pwd-{0}", count * multiply);
25. sw.Start();
26. sqlComm.ExecuteNonQuery();
27. sw.Stop();
28. }
29. //每插⼊10万条数据后,显⽰此次插⼊所⽤时间
30. Console.WriteLine(string.Format("Elapd Time is {0} Milliconds", sw.ElapdMilliconds));
31. }
32. }
33. catch (Exception ex)
34. {
35. throw ex;
36. }
去就色
37. finally
38. {
39. sqlConn.Clo();
40. }
41.
42. Console.ReadLine();
Stopwatch sw = new Stopwatch(); SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);//连接数据库 SqlCommand sqlComm = new SqlCommand(); sqlComm.CommandText = string.Format("inrt into
BulkTestTable(Id,UrName,Pwd)values(@p0,@p1,@p2)");//参数化SQL sqlComm.Parameters.Add("@p0", SqlDbType.Int); sqlComm.Parameters.Add("@p1", SqlDbType.NVarChar); sqlComm.Parameters.Add("@p2", SqlDbType.VarChar);
sqlComm.CommandType = CommandType.Text; sqlComm.Connection = sqlConn; sqlConn.Open(); try { //循环插⼊100万条数据,每次插⼊10万条,插⼊10次。 for (int multiply = 0; multiply < 10; multiply++) { for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++) { sqlComm.Parameters["@p0"].Value = count; sqlComm.Parameters["@p1"].Value = string.Format("Ur-{0}", count * multiply); sqlComm.Parameters["@p2"].Value = string.Format("Pwd-
{0}", count * multiply); sw.Start(); sqlComm.ExecuteNonQuery(); sw.Stop(); } //每插⼊10万条数据后,显⽰此次插⼊所⽤时间
Console.WriteLine(string.Format("Elapd Time is {0} Milliconds", sw.ElapdMilliconds)); } } catch (Exception ex) {
throw ex; } finally { sqlConn.Clo(); } Console.ReadLine();
耗时图如下:
由于运⾏过慢,才插⼊10万条就耗时72390 milliconds,所以我就⼿动强⾏停⽌了。
下⾯看⼀下使⽤Bulk插⼊的情况:
bulk⽅法主要思想是通过在客户端把数据都缓存在Table中,然后利⽤SqlBulkCopy⼀次性把Table中的数据插⼊到数据库代码如下:
[c-sharp]
1. public staticvoid BulkToDB(DataTable dt)
2. {
3. SqlConnection sqlConn = new SqlConnection(
4. ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
5. SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);单片机原理
6. bulkCopy.DestinationTableName = "BulkTestTable";
7. bulkCopy.BatchSize = dt.Rows.Count;
蒜苗炒腊肉的做法
8.
9. try
10. {
11. sqlConn.Open();
12. if (dt != null && dt.Rows.Count != 0)
13. bulkCopy.WriteToServer(dt);
14. }
15. catch (Exception ex)
16. {
17. throw ex;
18. }
19. finally
20. {
面积的单位是什么
21. sqlConn.Clo();
22. if (bulkCopy != null)
23. bulkCopy.Clo();
24. }
25. }
26.
27. public static DataTable GetTableSchema()
28. {
29. DataTable dt = new DataTable();
30. dt.Columns.AddRange(new DataColumn[]{
铅华洗尽
31. new DataColumn("Id",typeof(int)),
32. new DataColumn("UrName",typeof(string)),
33. new DataColumn("Pwd",typeof(string))});
34.
35. return dt;
36. }
37.
38. static void Main(string[] args)
39. {
40. Stopwatch sw = new Stopwatch();
41. for (int multiply = 0; multiply < 10; multiply++)
42. {
43. DataTable dt = Bulk.GetTableSchema();
44. for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)
45. {
46. DataRow r = dt.NewRow();
47. r[0] = count;
48. r[1] = string.Format("Ur-{0}", count * multiply);
49. r[2] = string.Format("Pwd-{0}", count * multiply);
50. dt.Rows.Add(r);
51. }
52. sw.Start();
53. Bulk.BulkToDB(dt);
54. sw.Stop();
55. Console.WriteLine(string.Format("Elapd Time is {0} Milliconds", sw.ElapdMilliconds));
56. }
57.
58. Console.ReadLine();
59. }
public static void BulkToDB(DataTable dt) { SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString); SqlBulkCopy bulkCopy = new
SqlBulkCopy(sqlConn); bulkCopy.DestinationTableName = "BulkTestTable"; bulkCopy.BatchSize = dt.Rows.Count; try { sqlConn.Open(); if (dt != null && dt.Rows.Count != 0) bulkCopy.WriteToServer(dt)
; } catch (Exception ex) { throw ex; } finally { sqlConn.Clo(); if (bulkCopy != null) bulkCopy.Clo(); } } public static DataTable GetTableSchema() { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[]{ new DataColumn("Id",typeof(int)), new
DataColumn("UrName",typeof(string)), new DataColumn("Pwd",typeof(string))}); return dt; } static void Main(string[] args) { Stopwatch sw = new Stopwatch(); for (int multiply = 0; multiply < 10; multiply++) { DataTable dt = Bulk.GetTableSchema(); for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++) { DataRow r = dt.NewRow(); r[0] = count; r[1] = string.Format("Ur-{0}", count * multiply); r[2] = string.Format("Pwd-{0}", count * multiply); dt.Rows.Add(r); } sw.Start(); Bulk.BulkToDB(dt); sw.Stop(); Console.WriteLine(string.Format("Elapd Time is {0} Milliconds", sw.ElapdMilliconds)); } Console.ReadLine(); }
耗时图如下:
可见,使⽤Bulk后,效率和性能明显上升。使⽤Inrt插⼊10万数据耗时72390,⽽现在使⽤Bulk插⼊100万数据才耗时17583。
最后再看看使⽤表值参数的效率,会另你⼤为惊讶的。
晋升祝福语表值参数是SQL Server 2008新特性,简称TVPs。对于表值参数不熟悉的朋友,可以参考最新的book online,我也会另外写⼀篇关于表值参数的博客,不过此次不对表值参数的概念做过多的介绍。⾔归正传,看代码:英语四级口试
[c-sharp]
1. public staticvoid TableValuedToDB(DataTable dt)
2. {
3. SqlConnection sqlConn = new SqlConnection(
4. ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
5. const string TSqlStatement =
6. "inrt into BulkTestTable (Id,UrName,Pwd)" +
7. " SELECT nc.Id, nc.UrName,nc.Pwd" +
8. " FROM @NewBulkTestTvp AS nc";
9. SqlCommand cmd = new SqlCommand(TSqlStatement, sqlConn);
10. SqlParameter catParam = cmd.Parameters.AddWithValue("@NewBulkTestTvp", dt);
11. catParam.SqlDbType = SqlDbType.Structured;
12. //表值参数的名字叫BulkUdt,在上⾯的建⽴测试环境的SQL中有。
13. catParam.TypeName = "dbo.BulkUdt";
14. try
15. {
16. sqlConn.Open();
17. if (dt != null && dt.Rows.Count != 0)
18. {
19. cmd.ExecuteNonQuery();
20. }
21. }
22. catch (Exception ex)
23. {
24. throw ex;
25. }
26. finally
27. {
28. sqlConn.Clo();
29. }
30. }
一帮人31.