简体   繁体   中英

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. 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. I would suggest moving the try/catch to inside the using(tran=...) block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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