#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
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
※不望朝进大步§※§但求日积点滴※