为什么getGeneratedKeys()返回" GENERATED_KEY"作为列名? [英] Why does getGeneratedKeys() return "GENERATED_KEY" as column name?

查看:259
本文介绍了为什么getGeneratedKeys()返回" GENERATED_KEY"作为列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm playing with the JDBC/MySQL 5.1. I created an insert query to insert some data into a table and want to return the generated key from the newly created row. However, when I go to reference the column by "id" which is my PK and auto-increment column.

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 作为列名?

So, my question: Why does ResultSet.getGeneratedKeys use GENERATED_KEY as the column name?

推荐答案


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

You shouldn't retrieve these columns by name. Only by index, since there can only ever be one column with MySQL and auto_increments that returns value(s) that can be exposed by Statement.getGeneratedKeys().

目前MySQL服务器没有直接返回信息,因为
将能够以
有效的方式按名称检索这些列,这就是为什么我将此标记为以后修好
,因为我们可以,一旦服务器以
a的方式返回驱动程序可以使用的信息。

Currently the MySQL server doesn't return information directly that would make the ability to retrieve these columns by name in an efficient manner possible, which is why I'm marking this as "to be fixed later", since we can, once the server returns the information in a way that the driver can use.

来自此处(2006年!)。

From here (in 2006!).

这篇关于为什么getGeneratedKeys()返回" GENERATED_KEY"作为列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆