MySQL/JDBC : How to "atomically" remove rows and then add one new row

标签 mysql jdbc atomic

我有以下场景:

1. DELETE FROM my_table WHERE user_id = ?;    // Prepared statement.
2. INSERT INTO my_table VALUES(?, ?, ..., ?); // Also a prepared statement.

问题1

假设两个客户端(我们称它们为AB)执行上面的两个操作。 是否有可能所有四个操作都按如下方式执行?

  • A 执行操作 1。
  • B 执行操作 1。
  • A 执行操作 2。
  • B 执行操作 2。

(当我只需要 1 行时,这将引入 2 行。)

问题2

如果问题 1 的答案是肯定的,我该如何禁用上述“交错”。或者换句话说,我如何确保 A 首先执行 操作 1 和 2,然后然后 B 执行这两个操作。另外,如何使用 JDBC 完成此操作?

最佳答案

您描述的情况正是大多数数据库管理系统支持 Transaction management 概念的原因。 .

A transaction is a set of one or more statements that is executed as a unit, so either all of the statements are executed, or none of the statements is executed.

术语“原子”用于指代上述引用中“作为一个单元”发生的 Action 。

交易实现的进一步细化是 Transaction isolation 的概念。 .它描述了当多个进程在事务生效的数据库上操作时应该如何表现。在您的具体情况下,

“我怎样才能确保 A 先执行操作 1 和 2,然后 B 执行这两个操作”

听起来您想使用 TRANSACTION_SERIALIZABLE 的事务隔离级别(顾名思义)确保以有效“串行”的方式管理多个事务,例如,强制 process_B等待 process_A 的事务完成。

关于MySQL/JDBC : How to "atomically" remove rows and then add one new row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47462257/

相关文章:

mysql - 比较2列值后如何按升序排序并且条件以较低者为准?

用于特定查询的 jdbc getMetaData

mysql - SORM 与 MySQL 空闲连接

由 ResultSet 支持的 Java 迭代器

c - 如何在不使用 C 中的锁的情况下以原子方式修改结构元素?

php - 使用codeigniter在mysql中插入多行: it inserts only one row and in that one row stores only one first character

mysql - rake gem :install shows error (database is not migrating)/

php - 来自 mysql 数据库表行的是和否值的总数

c++ - 为什么 std::atomic_thread_fence 有 "C"链接?

c# - 这个 "Int64"代理是原子的吗?