一尘不染

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

java

这个SQL Server片段的PLSQL(Oracle)等效项是什么?

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");

阅读 265

收藏
2020-09-08

共1个答案

一尘不染

通常,
您将使用Statement#getGeneratedKeys()此方法,但是到目前为止(仍然)Oracle
JDBC驱动程序不支持此方法。

最好的办法是 要么
化妆使用的CallableStatement一个RETURNING条款:

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.CURRVAL后开火INSERT

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();
    // ...
2020-09-08