Using Transactions with MySQL and Delphi

Discussion of open issues, suggestions and bugs regarding MyDAC (Data Access Components for MySQL) for Delphi, C++Builder, Lazarus (and FPC)
Post Reply
jamesgjatkin
Posts: 2
Joined: Tue 02 Aug 2011 11:16

Using Transactions with MySQL and Delphi

Post by jamesgjatkin » Tue 02 Aug 2011 13:02

Hi all,

I have just downloaded the evaluation of MyDAC with the aim to upgrade a Delphi application from Interbase to MySQL.

The method in which Transactions are used appears to differ though. Based on the existing code, the translation should be:

Code: Select all

  xTransaction := TMyTransaction.Create(nil);
  xMyCommand := TMyCommand.Create(nil);
  xMyCommand.Connection := MyConnection1;
  xMyCommand.Transaction := xTransaction;
  xTransaction.StartTransaction();
  xMyCommand.SQL.Add('INSERT INTO TBL (A,B) VALUES ("1", "2")');
  xMyCommand.Prepare();
  xMyCommand.Execute();
  xTransaction.Commit();
As TMyCommand does not appear to have "Transaction" available, how can ths be done?

Thanks,

James

AndreyZ

Post by AndreyZ » Wed 03 Aug 2011 08:07

Hello,

The point is that transaction support in MySQL and InterBase differs greatly. To work with MySQL transactions, you should use the StartTransaction, Commit, and Rollback methods of the TMyConnection component. Here is a code example:

Code: Select all

xMyCommand := TMyCommand.Create(nil);   
xMyCommand.Connection := MyConnection1; 
xMyCommand.Connection.Open;
xMyCommand.Connection.StartTransaction;
xMyCommand.SQL.Add('INSERT INTO TBL (A,B) VALUES ("1", "2")');
xMyCommand.Prepare;
xMyCommand.Execute;
xMyCommand.Connection.Commit;

jamesgjatkin
Posts: 2
Joined: Tue 02 Aug 2011 11:16

Post by jamesgjatkin » Wed 03 Aug 2011 09:17

Thanks for the really quick response…

Ok, that all looks good…

As the Transactions look like they are tied to the Connection, what happens in the event that you have multiple threads within the same application, using the same connection each starting their own transactions at the same time – will this work ok, or do the transactions have to be ‘queued’?

AndreyZ

Post by AndreyZ » Wed 03 Aug 2011 14:52

The point is that you should have a separate connection per each thread. In this case your application will be thread-safe and you will not have the problem with transactions.

Post Reply