Duplicate key / PostError

Discussion of open issues, suggestions and bugs regarding MyDAC (Data Access Components for MySQL) for Delphi, C++Builder, Lazarus (and FPC)
Post Reply
mierlp
Posts: 29
Joined: Thu 26 Jan 2006 08:34
Location: Nederlands

Duplicate key / PostError

Post by mierlp » Thu 11 Jun 2009 22:06

hi,

My MYSQL INNODB table contains 2 fields called :
- city_id (int / autoinc)
- city_name (var)

There's a unique index on city_name. Because i would like to prevent
duplicate city names i have a OnPostError event for this query with the code below. Within my datamodule i defined const. like this:

const
{Declare constants we're interested in}
ER_DUP_KEY = 1062;

The OnPostError event has this code:

Code: Select all

procedure TdmTables.qry_cityPostError(DataSet: TDataSet; E: EDatabaseError;
  var Action: TDataAction);
begin
  if (E is EMyError) then begin
     if (EMyError(E).ErrorCode=ER_DUP_KEY) then begin
       Application.MessageBox('It's not allowed to enter duplicate names!.', 'Warning', MB_OK+MB_ICONEXCLAMATION+MB_DEFBUTTON1+MB_APPLMODAL);
       dmTables.qry_city.cancel;
       Abort;
    end;
  end;
end;
For some reason the message above is not showed and the applications
terminates after entering a duplicate name.

How to prevent this and is there some other code to prevent duplicates
or make the above code working.

Regards Peter

Dimon
Devart Team
Posts: 2910
Joined: Mon 05 Mar 2007 16:32

Post by Dimon » Fri 12 Jun 2009 07:03

To solve the problem try to change the following line:

Code: Select all

  Abort;
to the code:

Code: Select all

  Action := daAbort;

mierlp
Posts: 29
Joined: Thu 26 Jan 2006 08:34
Location: Nederlands

Post by mierlp » Fri 12 Jun 2009 14:59

Hi,

That also doesn't work. At runtime i get the message:

MySQLException with message #23000Duplicate key for ...

There's a unique index on the field city_name. Is this the right
error code for duplicate keys? or are ther other methods to
prevent it

Dimon
Devart Team
Posts: 2910
Joined: Mon 05 Mar 2007 16:32

Post by Dimon » Mon 15 Jun 2009 08:25

Error code for duplicate keys is equal to 1062, but the error message received from MySQL server is '#23000Duplicate entry 'filename' for key 2'.

I can't reproduce the problem with MySQLException arisen at runtime. This exception is raised on the internal level and it is processed by MyDAC. You can see this exception only if you run the application from IDE.

Post Reply