代码之家  ›  专栏  ›  技术社区  ›  Rohit Banga

SQL JDBC GetGeneratedKeys返回列“id”未找到,列类型未知

  •  8
  • Rohit Banga  · 技术社区  · 16 年前

    我想使用插入查询检索表中最近更新的值。

    这些是我的SQL表中的数据类型。

    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代码

       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`
    

    堆栈跟踪

        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
    
    2 回复  |  直到 10 年前
        1
  •  13
  •   Pascal Thivent    16 年前

    你需要打电话 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);
    
        2
  •  2
  •   muye    13 年前

    可能是因为sqlquery没有创建任何新记录! 在这种情况下,它将返回空的结果集 查看getGeneratedKeys()的规范

    推荐文章