#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