选择并删除事务 SQL 中的记录



我正在使用oracle作为我的数据库服务器。我有一个简单的sql表,它存储每个成员的代码。我想从表中删除代码,但也要获取它的值。

SQL> describe member_code_store;
 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 MEMBER                    NOT NULL NUMBER(38)
 CODE                      NOT NULL VARCHAR2(30)

所以我想在事务中运行以下查询

PreparedStatement pstmt = null;
ResultSet rs = null;
String query =
        "SELECT code FROM member_code_store where coupon=? AND rownum=1";
Connection connection = DBConnection.getConnection();
pstmt = connection.prepareStatement(query);
pstmt.setString(1, String.valueOf(3));
rs = pstmt.executeQuery();
rs.next();
String code = rs.getString(1);

立即删除代码

String query =
        "delete from member_code_store where coupon =? AND code=?;";
Connection connection = DBConnection.getConnection();
pstmt = connection.prepareStatement(query);
pstmt.setString(1, String.valueOf(3));
pstmt.setString(2, code);
rs = pstmt.executeUpdate();

上述代码的问题在于,删除代码的多个工作线程将获得相同的代码。如何封装事务,以便只锁定记录而不是锁定整个表。

还是我应该使用更有效的程序或软件包?

本质上你应该使用行锁。我展示的示例包括 nowait 选项,如果您尝试选择锁定的行并且您的代码必须处理该行,它将返回错误。

select code, rowid 
from member_code_store
where coupon=? AND rownum=1
for update of code nowait

保存 rowid,以便您有一个变量提供给 delete 语句

delete from member_code_store
where rowid = :row_id

最新更新