大家好,又见面了,我是你们的朋友全栈君。
一个体会记在此:
SqlTransaction.Dispose 如果之前没有提交事务,譔方法就会调用RollBack(Will rollback if not commited )。
之前写的代码:
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();
}
写事务可以节的写为:
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.
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/136708.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...