开发者

Handling MySQL transcations for two methods

开发者 https://www.devze.com 2023-03-31 03:59 出处:网络
I want to use MySQL Transactions to Rollback changes if any of the method fails. I referred to this example at StackOverflow: MySql and inserting last ID problem remains, but my problem is a bit diffe

I want to use MySQL Transactions to Rollback changes if any of the method fails. I referred to this example at StackOverflow: MySql and inserting last ID problem remains, but my problem is a bit different.

I have a code as below:

private void btnSave_Click(object sender, EventArgs e)
{
    btnSave.Enabled = false;
    int result1 = SaveBillDetails();
    int result2 = SaveBillItems();

    if ((result1 == 1) && (result2 == 1))
    {
        //Update old stock
        UpdateStock.ReduceStock(Convert.ToInt32(txtBillNo.Text), Convert.ToDateTime(dtpBillDate.Text));
        MessageBox.Show("Saved", "StockApp", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    btnSave.Enabled = true;
}

I want to call something like BeginTransaction just before SaveBillDetails and SaveBillItems is called. Both of these methods are not using transactions. I j开发者_开发知识库ust want to add transaction to the above code.


It may be possible to use System.TransactionScope with MySQL depending on which verison of .Net you are targeting and which version of the MySQL connector you are using - see this post

also see the discussion on this question


this is a common issue, assuming that you are in full control of your Data Access Layer design and implementation, you should have a method that creates a connection or transaction and returns it back then you modify your two Save methods to accept a transaction as parameter and use it in the command execution.

Very important to wrap usage of connection and transaction with using so objects are disposed properly.

0

精彩评论

暂无评论...
验证码 换一张
取 消