PLSQL JDBC:如何获取最后一行 ID?

2022-09-02 05:35:04

PLSQL(Oracle)相当于这个SQL服务器代码段吗?

BEGIN TRAN
INSERT INTO mytable(content) VALUES ("test") -- assume there's an ID column that is autoincrement
SELECT @@IDENTITY
COMMIT TRAN

在 C# 中,可以调用 myCommand.ExecuteScalar() 来检索新行的 ID。

如何在 Oracle 中插入新行,并让 JDBC 获取新 ID 的副本?

编辑:BalusC提供了一个非常好的起点。由于某种原因,JDBC 不喜欢命名参数绑定。这给出了“错误设置或注册的参数”SQLException。为什么会发生这种情况?

        OracleConnection conn = getAppConnection();
        String q = "BEGIN INSERT INTO tb (id) values (claim_seq.nextval) returning id into :newId; end;" ;
        CallableStatement cs = (OracleCallableStatement) conn.prepareCall(q);
        cs.registerOutParameter("newId", OracleTypes.NUMBER);
        cs.execute();
        int newId = cs.getInt("newId");

答案 1

通常情况下,你会使用 Statement#getGeneratedKeys() 来执行此操作(有关示例,另请参阅此答案),但 Oracle JDBC 驱动程序不支持此操作(仍然)。

您最好的选择是使用带有子句的 CallableStatementRETURNING

String sql = "BEGIN INSERT INTO mytable(id, content) VALUES (seq_mytable.NEXTVAL(), ?) RETURNING id INTO ?; END;";

Connection connection = null;
CallableStatement statement = null;

try {
    connection = database.getConnection();
    statement = connection.prepareCall(sql);
    statement.setString(1, "test");
    statement.registerOutParameter(2, Types.NUMERIC);
    statement.execute();
    int id = statement.getInt(2);
    // ...

或者在同一笔交易中之后触发:SELECT sequencename.CURRVALINSERT

String sql_insert = "INSERT INTO mytable(content) VALUES (?)";
String sql_currval = "SELECT seq_mytable.CURRVAL FROM dual";

Connection connection = null;
PreparedStatement statement = null;
Statement currvalStatement = null;
ResultSet currvalResultSet = null;

try {
    connection = database.getConnection();
    connection.setAutoCommit(false);
    statement = connection.prepareStatement(sql_insert);
    statement.setString(1, "test");
    statement.executeUpdate();
    currvalStatement = connection.createStatement();
    currvalResultSet = currvalStatement.executeQuery(sql_currval);
    if (currvalResultSet.next()) {
        int id = currvalResultSet.getInt(1);
    }
    connection.commit();
    // ...

答案 2

您可以使用 Oracle 的返回子句。

insert into mytable(content) values ('test') returning your_id into :var;

查看此链接以获取代码示例。您需要 Oracle 10g 或更高版本,以及新版本的 JDBC 驱动程序。


推荐