简体   繁体   English

在ASP网站上使用C#进行SQL事务

[英]Using SQL transactions with C# in ASP website

I am trying to code a method where a user can pass multiple sql statements in string array format. 我试图编写一个方法,用户可以以字符串数组格式传递多个sql语句。 and create a transaction. 并创建一个交易。 Rollback if nessesary. 如果有必要就回滚。 At the moment I get an error saying that the transaction needs a command to execute. 目前,我收到一条错误消息,指出该事务需要执行命令。 Any advice would be appreciated, Maybe another(or right) way of doing what I need done. 任何建议将不胜感激,也许是另一种(或正确的)做我需要做的事情的方式。 The following is the existing code. 以下是现有代码。

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;
    }
}

You need to pass the transaction to the command before executing it: 您需要在执行之前将事务传递给命令:

cmdCommand.Transaction = tran;

Furthermore, you might want to be careful. 此外,您可能要小心。 You're using the transaction tran in the try block, but referencing it afterwards in the catch block. 您在try块中using了事务tran ,但之后在catch块中引用了它。 I would suggest moving the try/catch to inside the using(tran=...) block. 我建议将try / catch移动到using(tran=...)块内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM