简体   繁体   English

JDBC 插入或更新实践

[英]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:当然,我可以写: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:或者,我也可以这样写: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编辑:在 MYSQL

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:例如,MySQL 允许您执行以下操作:

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

However, the above is not standard (SQL-92) compliant.但是,上述内容不符合标准 (SQL-92)。 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.它可能看起来不那么优雅,但它可能是 go 最安全的解决方案。

You might want to look at using the DBMS to do the check within a single statement ie use the SQL EXISTS condition: WHERE EXISTS or WHERE NOT EXISTS您可能希望查看使用 DBMS 在单个语句中进行检查,即使用 SQL EXISTS 条件: WHERE EXISTSWHERE NOT EXISTS

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.例如,在 DB2 中,您可以使用 MERGE INTO。 See here这里

This is probably the reason to switch to one of popular ORM solutions (Hibernate, Toplink, iBatis).这可能是切换到流行的 ORM 解决方案(Hibernate、Toplink、iBatis)之一的原因。 These tools "know" various SQL dialects and optimise your queries accrodingly.这些工具“了解”各种 SQL 方言并相应地优化您的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM