简体   繁体   中英

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: ''prepareStatement'', 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM