Virgil said:
By examining the properties of SQLException. The methods getErrorCode()
and/or getSQLState would lead you to the underlying cause of the exception.
Not easily. There are several ways you might do this:
1. getErrorCode() this is dependent on the database vendor (and perhaps
the JDBC driver as well).
2. getSqlState. There are two possible standards for these codes.
Possible values for an already existing row might be "23000", "40002" or
"44000".
3. getMessage() This again is database and JDBC driver dependent.
I don't see any "Write Once Run Anywhere" option here. In most cases
this approach will require individual testing and coding for each
database/driver combination. By contrast the query to find if the row
exists can be written to work unchanged on most databases, although as
you point out it is likely to be slower. Where a number of rows are to
be inserted/updated a batch query could be used to determine row
existence for many rows at a time. This would reduce the number of round
trips to the database and thus improve performance (at least where batch
queries are available and implemented sensibly).
Mark Thornton