gpt4 book ai didi

c# - 将 SQL Server 事务作为参数传递的最佳方法是什么

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:54 26 4
gpt4 key购买 nike

我知道使用“using”关键字和类似代码在 .net C# 中实现 SQL Server 事务的解决方案:

InsertDetails()
{
using (TransactionScope ts = new TransactionScope())
{
InsertName();//SQL functions to insert name into name table
Insertaddress();//SQL functions to insert address into address table
InsertPhoneNo();//SQL functions to insert phone number into contact table

ts.Complete();
}
}

但是举例来说,我希望将 sql server 事务作为参数传递给不同数据库查询的许多不同函数,而没有 using 语句示例。

在调用代码路径中的所有函数后,我想进行调用以提交数据,如果出现问题则执行回滚。

伪代码看起来像这样

InsertDetails()
{
var transaction = new Transaction();
var sqlcon = new SqlConnection();
InsertName(transaction, sqlcon);//SQL functions to insert name into name table
Insertaddress(transaction, sqlcon);//SQL functions to insert address into address table
InsertPhoneNo(transaction, sqlcon);//code to insert phone no into contact table
try
{
ts.commit();
}
catch(Exception ex)
{
ts.rollback();
}
}

最佳答案

注意 #1:TransactionScope 可以升级为使用 MSDTC,因此使用 SqlTransaction 有助于避免这种行为。

注意#2:默认情况下,TransactionScope 也将使用序列化隔离级别,这可能会在行/表锁定中过于激进。因此,您可能希望在使用 TransactionScope 时更改该行为。更多详情请参阅:Why is System.Transactions TransactionScope default Isolationlevel Serializable

使用 SQLTransaction

坚持你的伪代码示例,我会像这样重写:

InsertDetails()
{
using (var sqlcon = new SqlConnection(<connectionString>))
{
sqlcon.Open();

// Create transaction to be used by all commands.
var transaction = sqlcon.BeginTransaction();

try
{
InsertName(transaction, sqlcon);//SQL functions to insert name into name table
Insertaddress(transaction, sqlcon);//SQL functions to insert address into address table
InsertPhoneNo(transaction, sqlcon);//code to insert phone no into contact table

transaction.commit();
}
catch(Exception ex)
{
transaction.rollback();
throw;
}
}
}

// Typical method implementation.
private void InsertName(SqlTransaction transaction, SqlConnection sqlcon)
{
using (var cmd = sqlcon.CreateCommand())
{
// This adds this command to the transaction.
cmd.Transaction = transaction;

// The rest is fairly typical.
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertStoredProcedureName";
... set parameters etc.
cmd.ExecuteNonQuery();
... handle any OUTPUT parameters etc.
}
}

这将为任何被调用方法中的所有错误回滚事务。

关于c# - 将 SQL Server 事务作为参数传递的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com