C# 將DataTable表中的資料批量插入到資料庫表中的方法

來源:互聯網
上載者:User

標籤:使用   style   view   catch   throw   row   opened   one   操作   

C#中有時候需要將記憶體中的資料批量插入到資料庫表中,使用for迴圈進行批量插入不但耗時而且會頻繁操作資料庫。

針對資料量很少的可以使用for迴圈插入,但是針對於資料量大的則不推薦使用for迴圈插入,推薦使用sql的塊處理插入。

塊處理不但耗時少而且不會頻繁對資料庫進行操作,只是需要注意的一點是DataTable中的列必須與表的列完全一致。

如下代碼是批量插入的一個函數,自測可用。

 1 #region 使用SqlBulkCopy將DataTable中的資料批量插入資料庫中   2         /// <summary>   3         /// 注意:DataTable中的列需要與資料庫表中的列完全一致。 4         /// 已自測可用。 5         /// </summary>   6         /// <param name="conStr">資料庫連接串</param> 7         /// <param name="strTableName">資料庫中對應的表名</param>   8         /// <param name="dtData">資料集</param>   9         public static void SqlBulkCopyInsert(string conStr, string strTableName, DataTable dtData)10         {11             try12             {13                 using (SqlBulkCopy sqlRevdBulkCopy = new SqlBulkCopy(conStr))//引用SqlBulkCopy  14                 {15                     sqlRevdBulkCopy.DestinationTableName = strTableName;//資料庫中對應的表名  16                     sqlRevdBulkCopy.NotifyAfter = dtData.Rows.Count;//有幾行資料  17                     sqlRevdBulkCopy.WriteToServer(dtData);//資料匯入資料庫  18                     sqlRevdBulkCopy.Close();//關閉串連  19                 }20             }21             catch (Exception ex)22             {23                 throw (ex);24             }25         }26         #endregion
View Code

  

C# 將DataTable表中的資料批量插入到資料庫表中的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.