Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

JDBC primary key doubt

  Asked By: Jeff    Date: Jan 22    Category: Java    Views: 952

I am tryin to execute an INSERT statement and want to
check if it violates the primary key constraint of the

i have a table named TABLE1 (COL1, COL2) with COL2
being the primary key.

i need to insert
(ABC , 1 )
(ABC, 2)
DEF, 3)
(EFG, 1)

as the 4th tuple violates the primary key
constraint... it should not be inserted.

my code currently does not insert it... but while
doing so...gives some errors.
is there ne way...this can be done w/o the errors??



4 Answers Found

Answer #1    Answered By: Brian Ross     Answered On: Jan 22

u can write a trigger for before insert  statement on your table  that pybass this
or try catch and ignore your exception. or write an stored procedure to do the
operation or use sequences or check before insert or .... or.... or ... its up
to u.

Answer #2    Answered By: Heidi Larson     Answered On: Jan 22

You don't want any message if a violation occurs???
If you're not, I think that the best way to do this is a stored procedure
directly from the database. Case your RDBMS does not supports procedures, I
suggest you to create a function "insert" and before the insert  use a "select
count(*) from table1 where col2 = id" statement  to check if the record exists.

Answer #3    Answered By: Nagina Mian     Answered On: Jan 22

you can also do this without error by enclosing the
statement.executeUpdate or whatever u r using directly
in the try and catch... e.g.

try // main block for connection establishment etc.
.. prepared Statement

loop {
try {
execute statement;
} catch (SQLException e){}

} catch ()

Answer #4    Answered By: Whitney Cruz     Answered On: Jan 22

could just run the values through a SELECT first and see if you get any

resultSet = stmt.executeQuery("select primaryKey where primaryKey=VALUE");

if (!resultSet.next()){
..do update

Didn't find what you were looking for? Find more on JDBC primary key doubt Or get search suggestion and latest updates.