Help with using TMyCommand with transaction please?

Discussion of open issues, suggestions and bugs regarding MyDAC (Data Access Components for MySQL) for Delphi, C++Builder, Lazarus (and FPC)
Post Reply
docH
Posts: 59
Joined: Sun 22 Dec 2013 15:18

Help with using TMyCommand with transaction please?

Post by docH » Sun 11 Jan 2015 10:48

I'm using a TMyCommand component in a Delphi application communicating with a remote MySQL database to execute a transaction with several statements. Any one of these statements might cause an error and if it does I want to roll back all of the statements, ie the whole transaction.

I am using the code below but I'm not convinced it is correctly detecting an error and doing the rollback every time as the error message isn't shown. Please can somebody take a look at it and tell me if it should work OK and if not, how I should alter it to do what I want?

Code: Select all

sql := ''
+ 'START TRANSACTION; '
+  'Insert into ....'       // lots of statements that might cause an error
+  'Delete from ...  '  
etc
+ ' COMMIT; '  ;

try
 MyCommand1.SQL.Clear;
 MyCommand1.SQL.Add(sql);
 MyCommand1.Execute;

 //if we get here then the sql went OK 

except    //if we get here then the sql caused an error somewhere
     on E : Exception do
         begin
         showmessage('Error in transaction '); 
         MyCommand1..SQL.Clear ;
         MyCommand1..SQL.Add('ROLLBACK; ');
         MyCommand1..Execute;
         end; //on E : Exception
end; //try  - except

ViktorV
Devart Team
Posts: 3168
Joined: Wed 30 Jul 2014 07:16

Re: Help with using TMyCommand with transaction please?

Post by ViktorV » Mon 12 Jan 2015 13:03

To work with MySQL transactions, we recommend using the StartTransaction, Commit, and Rollback methods of the TMyConnection component. Here is a code example:

Code: Select all

sql := ''
  +  'Insert into ....'       // lots of statements that might cause an error
  +  'Delete from ...  '  
  etc
if not MyCommand1.Connection.InTransaction then
  MyCommand1.Connection.StartTransaction;
try
  MyCommand1.SQL.Clear;
  MyCommand1.SQL.Add(sql);
  MyCommand1.Execute;
  MyCommand1.Connection.Commit;

//if we get here then the SQL went OK 

except    //if we get here then the SQL caused an error somewhere
  on E : Exception do
  begin
    Showmessage('Error in transaction '); 
    MyCommand1.Connection.Rollback;
  end; //on E : Exception
end; //try  - except

docH
Posts: 59
Joined: Sun 22 Dec 2013 15:18

Re: Help with using TMyCommand with transaction please?

Post by docH » Mon 12 Jan 2015 14:47

Ah, I see the difference, thank you. That looks more reliable.

ViktorV
Devart Team
Posts: 3168
Joined: Wed 30 Jul 2014 07:16

Re: Help with using TMyCommand with transaction please?

Post by ViktorV » Tue 13 Jan 2015 08:38

Feel free to contact us if you have any further questions about MyDAC.

Post Reply