java api里是这样说的
executeUpdate
int executeUpdate() throws SQLException
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Returns:
either (1) the row count for INSERT, UPDATE, or DELETE statements or (2) 0 for SQL statements that return nothing
在使用乐观锁的时候经常需要验证这个返回值来防止并发,但不同的JDBC驱动有不同的实现,并不是所有插入或更新都返回1,最近试了几个:
MySQL中:
会有1、2、3三种可能的返回值;
PostgreSQL中:
当T1没有主键时,插入返回值为0;
所以不能简单地靠返回值再决定回滚,即:
还有很多别的情况,欢迎讨论
executeUpdate
int executeUpdate() throws SQLException
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Returns:
either (1) the row count for INSERT, UPDATE, or DELETE statements or (2) 0 for SQL statements that return nothing
在使用乐观锁的时候经常需要验证这个返回值来防止并发,但不同的JDBC驱动有不同的实现,并不是所有插入或更新都返回1,最近试了几个:
MySQL中:
INSERT INTO T VALUES(?, ?) ON DUPLICATE KEY UPDATE c = ?;会有1、2、3三种可能的返回值;
PostgreSQL中:
INSERT INTO T1 VALUES(?, ?);当T1没有主键时,插入返回值为0;
所以不能简单地靠返回值再决定回滚,即:
int rowN = st.executeUpdate(sql);
if(rowN == 1) //错误代码
conn.rollback();
if(rowN < 1) //错误代码
conn.rollback();
还有很多别的情况,欢迎讨论
本文详细解析Java API executeUpdate方法的返回值及其在乐观锁场景下的应用,包括MySQL和PostgreSQL的实现差异。讨论了如何正确处理不同驱动返回的值,避免简单的判断导致的数据不一致问题。
1018

被折叠的 条评论
为什么被折叠?



