mysql transactions in asp.net?

徘徊边缘 提交于 2019-12-19 04:55:11

问题


Can you guys let me know the way of handling transactions in asp.net?

i.e. I have a few queries (Present in different functions and called under various situations) that have to be executed as a whole. So, how should I go about it?

Not sure of the syntax and the method/practice for writing the statements in .net (commit, rollback etc).

Kindly let me know. Also, plz point me to some good articles if possible. Thanks!!!


回答1:


I recommend using TransactionScope, because you can use it no mater what DB you are using. You can even do distributed transactions (operations against multiple databases within the same transaction) with it.

You can refer to a link for a code example, but in general, you do this:

try
{
    using (TransactionScope scope = new TransactionScope())
    {
        using (MySqlConnection connection1 = new MySqlConnection (connectionString))
        {
            // Opening the connection automatically enlists it in the 
            // TransactionScope as a lightweight transaction.
            connection1.Open();

            // create the DB commands and perform the DB operations
            .
            .
            .

            // The Complete method commits the transaction. If an exception has been thrown,
            // Complete is not called and the transaction is rolled back.
            scope.Complete();    
        }
    }
}
catch (Exception e)
{
    // something went wrong, handle the exception accordingly. Note
    // that since we did not call TransactionScope.Complete, nothing
    // gets committed to the DB.
}



回答2:


Here's another starter for TransactionScope: Implementing an Implicit Transaction using Transaction Scope




回答3:


Don't know much about TransactionScope, but I just use the normal IDbTransaction like this:

IDbConnection conn = null;
IDbCommand cmd = null;
IDbTransaction tran = null;

try
{
    conn = DatabaseUtil.GetConnection(); //Get the connection somehow
    cmd = conn.CreateCommand();

    tran = conn.BeginTransaction();
    cmd.Transaction = tran;


    //Do your DB Work

    tran.Commit();
}
catch (SystemException ex)
{
    tran.Rollback();
}
finally
{
    if (conn != null) conn.Close();
}

With the IDb classes you are DB independent too to a certain degree.




回答4:


If its a local transaction you can also use ado.net's transaction object. TransactionScope will handle distributed transactions if needed but requires MSDTC to be configured if a transaction is promoted to a distributed transaction.

http://msdn.microsoft.com/en-us/library/2k2hy99x.aspx

Both are in the System.Transactions Namespace http://msdn.microsoft.com/en-us/library/system.transactions.aspx



来源:https://stackoverflow.com/questions/3321006/mysql-transactions-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!