Skip to main content
 首页 » 编程设计

c#之在 ASP 网站中使用带有 C# 的 SQL 事务

2024年02月13日15sky-heaven

我正在尝试编写一种方法,用户可以在其中以字符串数组格式传递多个 sql 语句。并创建交易。必要时回滚。目前我收到一条错误消息,说交易需要一个命令来执行。任何建议将不胜感激,也许另一种(或正确的)方式来做我需要做的事情。以下是现有代码。

public bool Scalar(params string[] sqlTexts) 
{ 
    SqlTransaction tran = null; 
 
    try 
    { 
        using (SqlConnection connection = new SqlConnection(strConnectionString)) // Auto dispose of connection 
        { 
            connection.Open(); // Open the connection 
            using (tran = connection.BeginTransaction()) 
            { 
                using (SqlCommand cmdCommand = connection.CreateCommand()) // Auto dispose of command 
                { 
                    foreach (string currentSQL in sqlTexts) 
                    { 
                        cmdCommand.CommandText = currentSQL; 
                        cmdCommand.ExecuteScalar(); 
                    } 
                } 
 
                tran.Commit(); 
            } 
        } 
        return true; 
    } 
    catch (Exception) 
    { 
        if (tran != null) 
            tran.Rollback(); 
        return false; 
    } 
} 

请您参考如下方法:

在执行之前需要将事务传递给命令:

cmdCommand.Transaction = tran; 

此外,您可能需要小心。您在 try block 中使用事务 tran,但随后在 catch block 中引用它。我建议将 try/catch 移动到 using(tran=...) block 内。