Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC insert or update practice

I need to insert a record to table if the record doesn't exist, and to update a record if the record exists in the table. Of course, I can write: p-code:

SELECT * FROM table1 WHERE id='abc' by JDBC
if(exists)
   UPDATE table1 SET ... WHERE id='abc' by JDBC;
else
   INSERT INTO table1... by JDBC;

However, I don't think the code is elegant. Alternatively, I can also write it in this way: p-code:

int row = Statement.executeUpdate("INSERT INTO table1...", 2);
if(row==0)
  update table1 SET ... WHERE id='abc' by JDBC;

Do you think the latter way is better and faster? Thanks!

EDIT: in MYSQL

like image 236
卢声远 Shengyuan Lu Avatar asked Jun 06 '11 13:06

卢声远 Shengyuan Lu


3 Answers

It depends on what type of database your are using and whether or not you can take advantage of database specific features. MySQL for instance lets you do the following:

INSERT INTO territories (code, territory) VALUES ('NO', 'Norway')
ON DUPLICATE KEY UPDATE territory = 'Norway'

However, the above is not standard (SQL-92) compliant. That is, it will most likely not work on all databases. In other words, you would have to stick with the code as you have written it. It might not look that elegant, but it is probably the most safe solution to go with.

like image 57
sbrattla Avatar answered Nov 03 '22 23:11

sbrattla


You might want to look at using the DBMS to do the check within a single statement i.e. use the SQL EXISTS condition: WHERE EXISTS or WHERE NOT EXISTS

like image 4
planetjones Avatar answered Nov 04 '22 00:11

planetjones


Maybe the database you are using has an insert or update feature which solves this automatically for you. In DB2 you can use MERGE INTO for example. See here

like image 2
Kai Avatar answered Nov 04 '22 01:11

Kai