c#批量插入資料到資料庫【支援事務操作】

來源:互聯網
上載者:User
  #region  批量插入資料到資料庫
            DateTime startTime; 
            private bool SqlBulkCopy(DataTable dt)
            {

                try
                {
                    startTime = DateTime.Now;
                    //資料大量匯入sqlserver,建立執行個體    SqlBulkCopyOptions.UseInternalTransaction採用事務  複製失敗自動復原
                    System.Data.SqlClient.SqlBulkCopy sqlbulk = new System.Data.SqlClient.SqlBulkCopy(System.Configuration.ConfigurationSettings.AppSettings["ConStr"], SqlBulkCopyOptions.UseInternalTransaction);
                    sqlbulk.SqlRowsCopied +=
                    new SqlRowsCopiedEventHandler(OnRowsCopied); //訂閱複製完成後的方法,參數是 sqlbulk.NotifyAfter的值
                    sqlbulk.NotifyAfter = dt.Rows.Count;

                    //目標資料庫表名
                    sqlbulk.DestinationTableName = "T_TempUpLoadTC";
                    //資料集欄位索引與資料庫欄位索引映射
                    sqlbulk.ColumnMappings.Add(0, "userName");
                    sqlbulk.ColumnMappings.Add(1, "JiFenCount");
                    //匯入
                    sqlbulk.WriteToServer(dt);
                    sqlbulk.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally 
                {
                    dt.Dispose();
                }
            }
        

            //複製完成後的處理事件
            private void OnRowsCopied(object sender, SqlRowsCopiedEventArgs args)
            {
                lblCounter.Text += args.RowsCopied.ToString() + " 條記錄已匯入";
                TimeSpan copyTime = DateTime.Now - startTime;
                lblCounter.Text += "  花費時間:" + copyTime.Seconds.ToString() + "." +
                copyTime.Milliseconds.ToString() + " 秒";
            }
          #endregion

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.