Page 1 of 1

Duplicate key / PostError

Posted: Thu 11 Jun 2009 22:06
by mierlp
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

Posted: Fri 12 Jun 2009 07:03
by Dimon
To solve the problem try to change the following line:

Code: Select all

  Abort;
to the code:

Code: Select all

  Action := daAbort;

Posted: Fri 12 Jun 2009 14:59
by mierlp
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

Posted: Mon 15 Jun 2009 08:25
by Dimon
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.