数据库插入速度比较

一、使用EF插入,用时8135ms。

 1         Stopwatch stopWatch = new Stopwatch();
 2             stopWatch.Start();
 3             using (var content = new HardwareContext())
 4             {
 5                 for(int i = 20; i < 1000; i++)
 6                 {
 7                     HardwareLimited hardwareLimited = new HardwareLimited
 8                     {
 9                         id = i,
10                         DataId = "00000000000502",
11                         IsEnable = true
12                     };
13                     content.HardwareLimiteds.Add(hardwareLimited);
14                 }
15                 content.SaveChanges();
16             }
17             stopWatch.Stop();
18             MessageBox.Show(stopWatch.ElapsedMilliseconds.ToString());

二、直接插入,用时1.745ms。

 1             string sql = "";
 2             Stopwatch stopWatch = new Stopwatch();
 3             stopWatch.Start();
 4             for (int i = 20; i < 1000; i++)
 5             {
 6                 sql += "  insert into  [ProjectTS].[dbo].[MSHardwareLimited] (id,DataId,IsEnable)values('"+i.ToString()+ "','00000000000502',1) ";
 7             }
 8             DBHelp.ExecuteSql(sql);
 9             stopWatch.Stop();
10             MessageBox.Show(stopWatch.ElapsedMilliseconds.ToString());

三、使用SqlBulkCopy插入,用时244ms。

 1          DataTable dataTable = new DataTable();
 2             dataTable.Columns.Add("id", typeof(int));
 3             dataTable.Columns.Add("DataId", typeof(string));
 4             dataTable.Columns.Add("IsEnable", typeof(bool));
 5             for (int i = 20; i < 1000; i++)
 6             {
 7                 DataRow dataRow = dataTable.NewRow();
 8                 dataRow["id"] = i;
 9                 dataRow["DataId"] = "00000000000502";
10                 dataRow["IsEnable"] = true;
11                 dataTable.Rows.Add(dataRow);
12             }
13             Stopwatch stopWatch = new Stopwatch();
14             stopWatch.Start();
15             using (SqlConnection conn = new SqlConnection(DBHelp.connectString))
16             {
17                 conn.Open();
18                 using (SqlBulkCopy bulk = new SqlBulkCopy(DBHelp.connectString))
19                 {
20                     bulk.BatchSize = 10000;
21                     bulk.DestinationTableName = "[ProjectTS].[dbo].[MSHardwareLimited]";
22                     bulk.ColumnMappings.Add("id", "id");
23                     bulk.ColumnMappings.Add("DataId", "DataId");
24                     bulk.ColumnMappings.Add("IsEnable", "IsEnable");
25                     bulk.WriteToServer(dataTable);
26                 }
27                 conn.Close();
28                 conn.Dispose();
29             }
30             stopWatch.Stop();
31             MessageBox.Show(stopWatch.ElapsedMilliseconds.ToString());

 

posted on 2017-04-14 11:24  yuekong2010  阅读(690)  评论(0编辑  收藏  举报