40

I'm reading very detailed tutorials on how to use transactions with database types and database engines, but I haven't found a guide that teaches me when and why I should use them.

I know transactions are usually used for banking, so when we work with money data, but I can imagine they are used in many other ways.

Today I'm working on a page with various INSERT statements for a relational database, and I wanted to know if this is one of the cases when I should use them.

I get an impression that I don't know the cases when the data can be partially lost (apart from coder errors) so I'm always worried about when I should use them.

Can someone explain or give some link with these fundamental rules?

I'm using MySQL 5.0.8. Should I use InnoDB for all tables that need transactions? If yes, is InnoDB slower than the common MyISAM but I shouldn't worry about that?

thanks

mc01
  • 3,652
  • 18
  • 24
vitto
  • 18,266
  • 30
  • 88
  • 128

6 Answers6

28

Basically any time you have a unit of work that is either sensitive to outside changes or needs the ability to rollback every change, if an error occurs or some other reason.

Look here for some excellent answers and their reasons for using them.

Community
  • 1
  • 1
Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
  • thanks for help, I've also found some tecnique to work with transactions here http://www.kennynet.co.uk/2008/12/02/php-pdo-nested-transactions/ – vitto Jan 29 '10 at 11:25
14

In addition to what Nick Craver wrote, you would want to use a transaction when you have a series of writes that need to be performed atomically; that is, they should all succeed or none should succeed.

danben
  • 77,526
  • 18
  • 119
  • 143
11

Transactions should be used when there is the possibility that either failure to complete or someone else reading or writing in the middle of your task could cause damage to the data. These include but are not limited to:

  • Reading from a table for subsequent deletion
  • Writing related data to multiple tables
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
6

You use transactions when you have a group of actions that must be atomic (either all succeed or none succeed) Wrapping these actions in a transaction allows you to rollback actions that have already succeeded when you encounter an error. It also ensures that the data you are working with is consistent as locks will be held until the transaction is complete.

Nate Heinrich
  • 1,805
  • 14
  • 14
0

In some frameworks, e.g. Spring, automatic transactions allow to re-execute a transaction if it failed.

Alexander Volkov
  • 7,438
  • 1
  • 44
  • 41
0

Mostly use for multiple same curd cases, where you want save changes for valid entries, for a multi steps form with multiple input for each step of those form s submit cases, and form submit after getting an external api feedback.. mainly when you want rollback your query for some return value.

AloneCoder
  • 1
  • 1
  • 4