Wait for other transaction to commit/rollback before beginning another transaction?

∥☆過路亽.° 提交于 2019-12-13 04:30:05

问题


How can I make my transactions to wait if there is still an un-committed/un-roll-backed transaction in MySQL?

Currently I do my transactions on the code side, not on the DB Stored Procedure side, like this:

cmd.Connection.BeginTransaction();
try {
    // db codes here
    cmd.Transaction.Commit();
} catch {
    cmd.Transaction.Rollback();
    throw;
} finally {
    cmd.Connection.Close();
}

I want for other transactions to wait until the previous transaction is finished. Since I have, in some of my stored proc, that gets the MAX(id) when inserting for a foreign keys, where id is an auto-incremented column that is also created on the same transaction. But it doesn't work on my current setup above when 2 transactions occur at the same time, what happened is like this:

Begin Trans1
Begin Trans2
Trans1: insert a values(); --id = 1
Trans2: insert a values(); --id = 1
Trans1: insert b(aid, col1) values((select MAX(id) from a), 'test'); --aid = 1
Trans2: insert b(aid, col1) values((select MAX(id) from a), 'test'); --aid = 1
Commit Trans1
Commit Trans2 --id = 2, aid = 1

What I was hoping is like this:

Begin Trans1
Wait Trans2
Trans1: insert a values(); --id = 1
Trans1: insert b(aid, col1) values((select MAX(id) from a), 'test'); --aid = 1
Commit Trans1
Begin Trans2
Trans2: insert a values(); --id = 2
Trans2: insert b(aid, col1) values((select MAX(id) from a), 'test'); --aid = 2
Commit Trans2

Is it possible like this?


回答1:


by using IsolationLevel.ReadCommitted you can avoid the access to the table involved in a transaction by other transaction

cmd.Connection.BeginTransaction(IsolationLevel.ReadCommitted);

or

you can use TransactionScope class. TransactionScope makes the Code block transactional,till the code is not committed the tables will be locked and if some other requests the same table then it will have to wait until the running transaction is committed or rolled back.

refer



来源:https://stackoverflow.com/questions/18457955/wait-for-other-transaction-to-commit-rollback-before-beginning-another-transacti

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