RETURN_GENERATED_KEYS doesn't work using JDBC ODBC
I'm trying to get insert ID while after inserting some data in my database.
String sql = "INSERT INTO ADI.DUMMY(dummy_data) VALUES('from database logger')";
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int extUptReturn = ps.executeUpdate(sql);
But I got this exception:
Java exception: ''java.lang.UnsupportedOperationException'';
thrown from class name: ''sun.jdbc.odbc.JdbcOdbcConnection'', method name: ''prepareState开发者_开发百科ment'', file: ''JdbcOdbcConnection.java'', line: '1762'
The ODBC bridge driver doesn't support it. Nothing to do against. Either replace the driver or live with it. I would just use a real JDBC driver instead of the poorly-developed, feature-lacking, bug-rich Sun ODBC bridge driver. Almost all self-respected server based RDBMS vendors provides a fullworthy JDBC driver for download at their homepage. Just Google "[vendorname] jdbc driver download" to find it. Here's an overview:
- MySQL JDBC driver
- PostgreSQL JDBC driver (note: older versions didn't support generated keys as well).
- Oracle JDBC driver (note: older versions didn't support generated keys as well).
- MSSQL JDBC driver (or performancewise better, the jTDS JDBC driver)
- DB2 JDBC driver is hard to find in IBM's online forest, but it's usually already included in the
/java
folder of the DB2 installation. - UCanAccess driver for Microsoft Access databases (more details here).
MAy be the JDBC implementation could not be supporting the sepcific opration. CHeck the JDBC driver used.
Try this example instead of Statement.RETURN_GENERATED_KEYS
:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection
.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
Where BRANCHID is the auto generated id
精彩评论