大家好,又见面了,我是你们的朋友全栈君。
一个体会记在此:
SqlTransaction.Dispose 如果之前没有提交事务,譔方法就会调用RollBack(Will rollback if not commited )。
之前写的代码:
代码语言:javascript复制 using (SqlConnection conn = dbo.CreateConnection as SqlConnection)
{
if (conn != null && conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlTransaction tran = conn.BeginTransaction();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran))
{
try
{
bulkCopy.BatchSize = 50;
bulkCopy.DestinationTableName = "ekeyv2_unbind";
bulkCopy.BulkCopyTimeout = 60;
// 映射表结构
bulkCopy.ColumnMappings.Add("ekey_company", "ekey_company");
bulkCopy.ColumnMappings.Add("ekey_sn", "ekey_sn");
bulkCopy.ColumnMappings.Add("unbind_status", "unbind_status");
bulkCopy.ColumnMappings.Add("retry_times", "retry_times");
bulkCopy.ColumnMappings.Add("create_time", "create_time");
bulkCopy.ColumnMappings.Add("user_id", "user_id");
bulkCopy.ColumnMappings.Add("account", "account");
bulkCopy.ColumnMappings.Add("ekey_type", "ekey_type");
bulkCopy.WriteToServer(table);
tran.Commit();
isSuccess = true;
}
catch
{
tran.Rollback();
isSuccess = false;
}
}
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
conn.Dispose();
}
写事务可以节的写为:
代码语言:javascript复制 using (SqlConnection conn = dbo.CreateConnection as SqlConnection)
{
if (conn != null && conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlTransaction tran = conn.BeginTransaction();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran))
{
bulkCopy.BatchSize = 50;
bulkCopy.DestinationTableName = "ekeyv2_unbind";
bulkCopy.BulkCopyTimeout = 60;
// 映射表结构
bulkCopy.ColumnMappings.Add("ekey_company", "ekey_company");
bulkCopy.ColumnMappings.Add("ekey_sn", "ekey_sn");
bulkCopy.ColumnMappings.Add("unbind_status", "unbind_status");
bulkCopy.ColumnMappings.Add("retry_times", "retry_times");
bulkCopy.ColumnMappings.Add("create_time", "create_time");
bulkCopy.ColumnMappings.Add("user_id", "user_id");
bulkCopy.ColumnMappings.Add("account", "account");
bulkCopy.ColumnMappings.Add("ekey_type", "ekey_type");
bulkCopy.WriteToServer(table);
}
tran.Commit();
}
注意:using(){},出了using,conn就会调用Dispose,故这里不用RollBack.
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/136708.html原文链接:https://javaforall.cn
如果您是在找激活码,但输入激活码后激活失败,最新激活码地址:https://javaforall.cn/127239.html