gpt4 book ai didi

java - PLSQL JDBC : How to get last row ID?

转载 作者:太空狗 更新时间:2023-10-29 22:31:31 24 4
gpt4 key购买 nike

此 SQL 服务器代码段的 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 不喜欢命名参数绑定(bind)。这会产生“错误设置或注册的参数”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");

最佳答案

通常您会使用 Statement#getGeneratedKeys()为此(另请参阅 this answer 的示例),但到目前为止(仍然)不受 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);
// ...

或者在同一事务中的INSERT 之后触发SELECT sequencename.CURRVAL:

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

关于java - PLSQL JDBC : How to get last row ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3552260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com