I am new to db programming.
I read everywhere that I can use trasactions to rollback my actions if I encounter problem down the road.
I would like to know about transactions:
- does a transaction “lock” the db ?
- If a locking happens, what happens to other users accessing the db ? is it possible that they may get an error message ? Should I programatically check for such an error and try again ?
Are there things to do to make my db ready for transactions ? like setting the autocommit to off ? Is there anything else ?
Is there a downside to using transactions ? It seems all good to me.
Thanks in advance!
The whole database is never locked, that would be very inefficient.
Rather, MySQL (depending on the storage engine), locks records and in some cases whole tables.
You need to make sure the storage engine is InnoDB, otherwise transactions are not possible.
Autocommit is a feature that exists in the connecting client only, it just issues a commit everytime you make changes to the DB.
Transactions will cause overhead and might cause significant performance problems. If you try to transactionally write to the same record (let’s say a hit-counter on your homepage) over and over again, then it locks this record and a lot of writes are blocked.
You should only use transactions if you need to provide consistency in your database, i.e. a bunch of records together should be written in 1 go, or not at all.