【问题标题】:Why does getGeneratedKeys() return "GENERATED_KEY" as column name?为什么 getGeneratedKeys() 返回“GENERATED_KEY”作为列名?
【发布时间】:2012-02-10 15:46:05
【问题描述】:

我正在使用 JDBC/MySQL 5.1。我创建了一个insert 查询来将一些数据插入到表中,并希望从新创建的行中返回生成的键。但是,当我通过“id”引用该列时,这是我的 PK 和自动增量列。

PreparedStatement ps = St0rm.getInstance().getDatabase("main")
        .prepare("INSERT INTO quests (name,minlevel,start_npc,end_npc) VALUES(?,?,?,?)", true); // creates a prepared statement with flag RETURN_GENERATED_KEYS

// ...

int affected = ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();
if (affected > 0 && keys.next()) {
   St0rm.getInstance().getLogger().warning(String.format("ID Column Name: %s", keys.getMetaData().getColumnName(1))); // says the column name is: GENERATED_KEY

   q = new Quest(keys.getInt(1)); // column index from the generated key, no error thrown.

   q = new Quest(keys.getInt("id")); // actual column name, line throws a SQLException
   // ...
}

那么,我的问题是:为什么ResultSet.getGeneratedKeys 使用GENERATED_KEY 作为列名?

【问题讨论】:

    标签: java mysql jdbc


    【解决方案1】:

    您不应按名称检索这些列。仅按索引,因为 只有一列包含 MySQL 和 auto_increments 返回可由 Statement.getGeneratedKeys() 公开的值。

    目前 MySQL 服务器不直接返回信息 将使能够按名称检索这些列 可能的有效方式,这就是为什么我将其标记为“成为 稍后修复”,因为我们可以,一旦服务器返回信息 司机可以使用的一种方式。

    来自here(2006 年!)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2013-08-06
      • 2022-01-04
      相关资源
      最近更新 更多