简体   繁体   中英

sql jdbc getgeneratedkeys returns column “id” not found, column type unknown

I want to retrieve the most recently updated value in the table using an insert query.

these are the datatypes in my sql table.

Datatype:

int(11)      // primary key auto increment, not being assigned by sqlQuery
varchar(30)
timestamp    // has a default value. but i am explicit assigning it using CURRENT_TIMESTAMP
varchar(300)
varchar(300)
varchar(300)
int(11)
varchar(300)

java code

   statement.executeUpdate(sqlQuery, Statement.RETURN_GENERATED_KEYS);
   ResultSet rs = statement.getGeneratedKeys();
   System.out.println("here: " + rs.getMetaData().getColumnCount());
   System.out.println("here1: " + rs.getMetaData().getColumnName(1));
   // none of the following 3 works
   System.out.println("id: " + rs.getInt(1));
   System.out.println("id: " + rs.getInt("GENERATED_KEY"));
   System.out.println("id: " + rs.getInt("id"));
   for a bit of background see [this][1]
  `rs.getMetaData().getColumnTypeName(1)` tells me column type `UNKNOWN`

stack trace

    SEVERE: null
    java.sql.SQLException
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:815)
    at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5528)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5448)
  [1]: http://stackoverflow.com/questions/2853066/sql-java-get-value-assigned-to-auto-increment-primary-key

You need to call rs.next() :

int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
    autoIncKeyFromApi = rs.getInt(1);
} else {
    // do what you have to do
}
System.out.println(autoIncKeyFromApi);

Maybe it's because that the sqlQuery doesn't create any new record! In this case, it will return an empty ResultSet Look at the specification of getGeneratedKeys()

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