4

我正在尝试使用此问题中提到的方法(尽管我使用的是 Oracle 10g)来检索 JSP 中最后生成的自动增量 ID,例如 PHPmysql_insert_id()函数或 MySQLlast_insert_id()函数。getGeneratedKeys()

TRANSPORTER在 Oracle 数据库中有一个表,它有一个名为TRANSPORTER_IDtype的列,NUMBER(35, 0)它映射到BigDecimalJava 中的一个类型,它是一个序列生成的主键。

Connection con;
ResultSet rs;
PreparedStatement ps;
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "root";
String pwd = "root";

Class.forName("oracle.jdbc.OracleDriver").newInstance();
con = DriverManager.getConnection(url, user, pwd);

ps = con.prepareStatement("INSERT INTO transporter(transporter_name, transporter_website)VALUES(?, ?)");
ps.setString(1, "New");
ps.setString(2, "New Website");
ps.executeUpdate();

BigDecimal id = new BigDecimal(0);
rs = ps.getGeneratedKeys();

while (rs.next()) {
    id = rs.getBigDecimal("transporter_id");
}

out.println("The generated id is : " + id);

执行插入操作后,代码尝试rs = ps.getGeneratedKeys();在前面的while循环上方调用此方法,但失败并出现以下异常。

javax.servlet.ServletException:java.sql.SQLException:不允许操作

我已经尝试过Oracle JDBC Driver version - 10.2.0.5.0,当它失败时,我下载了更高版本,11.2.0.3.0但无济于事。可能是什么原因?

4

2 回答 2

5

I found some documentation about this. It's for 11g, but the situation probably won't be better for 10g.

The proximal cause of your error is probably the limitation that:

You need to access the ResultSet object returned from getGeneratedKeys method by position only

It seems the Oracle driver also requires you to identify the key column in order for it to retrieve the key column instead of just the ROWID. Sample code for this is included in the linked documentation.

于 2012-11-08T19:57:49.070 回答
0

ps = con.prepareStatement("INSERT INTO transporter(transporter_name, transporter_website)VALUES(?, ?)", new String[] {"transporter_id"});

于 2020-04-20T18:21:35.483 回答