Re: jdbc question

From: Thomas Kellerer (NNGNVRDSJEBN_at_spammotel.com)
Date: 12/30/04


Date: Thu, 30 Dec 2004 17:22:41 +0100

Sudsy wrote on 30.12.2004 15:05:

>> Why not do it the other way round? Update the row first, then check
>> the number of affected rows (which is returned by the executeUpdate()
>> method and is DBMS indepdent). If zero records were affected then the
>> record is not there and you can insert it. Thus you do not need to
>> rely on error codes for specific DBMS when catching an error during
>> the insert.
>
>
> I was wondering if/when someone would make this suggestion! The problem
> is, as others have mentioned, a matter of timing. Suppose you try an
> update and it fails. Between that point in time and the time you try an
> insert, another database client inserts a record with the same primary
> key. So now your insert fails and you have to fallback to performing
> the update again. KISS and perform an insert; iff it fails then try to
> update.

Without specific requirements there is no way telling which version is
better. If this is e.g. a data load that is performed during the night, the
the solution is absolutely valid. If this is a use case with highly
partioned data (each user edits different records) then it's valid as well,
if the situation is a highly dynamic entry system where the situation that
you sketched is very likely to happen, then obviously this is not a good
idea. On the other hand: if you expect more updates then inserts to be
successful, the overall performance would be *much* better this way because
the index lookup for the primary key is only needed once for the update but
twice for the inser/update combo.

I was simply offering a different solution. If it's feasible for the
situation of the OP is up to him (and he did not give information to us in
order to judge that)

Thomas



Relevant Pages

  • Re: jdbc question
    ... Update the row first, then check the ... > number of affected rows method ... > and is DBMS indepdent). ... So now your insert fails and you have to fallback to performing ...
    (comp.lang.java.programmer)
  • Re: jdbc question
    ... > Ann wrote: ... number of affected rows method ... and is DBMS indepdent). ... If zero records were affected then the record is ...
    (comp.lang.java.programmer)