I’m trying to retrieve the last generated auto-increment id in JSP something like the PHP mysql_insert_id() function or the MySQL last_insert_id() function using the getGeneratedKeys() method as mentioned in this question (I’m using Oracle 10g though).
I have a TRANSPORTER table in Oracle database which has a column named TRANSPORTER_ID of type NUMBER(35, 0) which is mapped to a BigDecimal type in Java and it is a sequence generated primary key.
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);
After the insertion operation is performed, the code attempts to invoke this method rs = ps.getGeneratedKeys();above the preceding while loop and it fails with following exception.
javax.servlet.ServletException: java.sql.SQLException: operation not
allowed
I have tried with the Oracle JDBC Driver version - 10.2.0.5.0 and when it failed I downloaded a higher version which is 11.2.0.3.0 but to no avail. What might be the reason?
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:
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.