Java sql jdbc getgeneratedkeys返回列“id”未找到,列类型未知
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2854774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sql jdbc getgeneratedkeys returns column "id" not found, column type unknown
提问by Rohit Banga
I want to retrieve the most recently updated value in the table using an insert query.
我想使用插入查询检索表中最近更新的值。
these are the datatypes in my sql table.
这些是我的 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 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
采纳答案by Pascal Thivent
You need to call rs.next()
:
您需要致电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);
回答by muye
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()
也许是因为 sqlQuery 没有创建任何新记录!在这种情况下,它会返回一个空的 ResultSet 看一下 getGeneratedKeys() 的规范