JDBC插入或更新实践

发布于 2024-11-13 08:16:07 字数 467 浏览 4 评论 0原文

如果记录不存在,我需要将记录插入到表中;如果表中存在记录,则需要更新记录。 当然,我可以写: 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;

但是,我认为代码并不优雅。 或者,我也可以这样写: p-code:

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

您认为后一种方式更好更快吗?谢谢!

编辑:在 MYSQL 中

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

橙幽之幻 2024-11-20 08:16:07

这取决于您使用的数据库类型以及您是否可以利用数据库特定功能。例如,MySQL 允许您执行以下操作:

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

但是,上述内容不符合标准 (SQL-92)。也就是说,它很可能不适用于所有数据库。换句话说,您必须坚持使用您编写的代码。它可能看起来不那么优雅,但它可能是最安全的解决方案。

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.

挽梦忆笙歌 2024-11-20 08:16:07

您可能希望考虑使用 DBMS 在单个语句中进行检查,即使用 SQL EXISTS 条件:WHERE EXISTSWHERE NOT EXISTS

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

我只土不豪 2024-11-20 08:16:07

也许您使用的数据库具有插入或更新功能,可以自动为您解决这个问题。例如,在 DB2 中,您可以使用 MERGE INTO。请参阅此处

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

无法回应 2024-11-20 08:16:07

这可能是切换到流行的 ORM 解决方案之一(Hibernate、Toplink、iBatis)的原因。这些工具“了解”各种 SQL 方言并相应地优化您的查询。

This is probably the reason to switch to one of popular ORM solutions (Hibernate, Toplink, iBatis). These tools "know" various SQL dialects and optimise your queries accrodingly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文