java 使用 JDBC PreparedStatement 在 MySql 中返回生成的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10488979/
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
Returning generated keys in MySql with JDBC PreparedStatement
提问by Paul Vargas
I'm programming with plain JDBCa DAOlayer because I only have 61.38 MBon Java Memoryin my Tomcat(service hosting). I have a table with an AUTO_INCREMENT
column in MySQL. The current implementation has no problems. But I would like to know the value that was generated in the AUTO_INCREMENT
column.
我用普通的编程JDBC一个DAO层,因为我只有 61.38 MB对Java内存在我的Tomcat(服务主机)。我AUTO_INCREMENT
在 MySQL 中有一个包含一列的表。当前的实现没有问题。但我想知道AUTO_INCREMENT
列中生成的值。
The current code looks as follows in the method that inserts a new row.
当前代码在插入新行的方法中如下所示。
public Integer store(MyBean bean) throws DAOException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement("INSERT ...");
if (bean.getSomeProperty() != null) {
ps.setShort(1, bean.getSomeProperty());
} else {
ps.setNull(1, Types.SMALLINT);
}
/* Other fields */
int rows = ps.executeUpdate();
if (rows == 1) {
// RETURN the generated value
}
return null;
} catch (SQLException e) {
throw new DAOException(e);
} finally {
...
}
}
I have seen that this is possible in Hibernate
, but because I have little memory, is not a feasible option.
我已经看到这在 中是可能的Hibernate
,但是因为我的记忆力很小,所以不是一个可行的选择。
I appreciate the help.
我很感激你的帮助。
回答by Mark Rotteveel
There are two ways:
有两种方式:
Using the JDBC concept of
getGeneratedKeys()
. See http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html#connector-j-examples-autoincrement-getgeneratedkeysOr use the MySQL function
LAST_INSERT_ID()
. See http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html#connector-j-examples-autoincrement-select
使用 JDBC 概念
getGeneratedKeys()
. 请参阅http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html#connector-j-examples-autoincrement-getgeneratedkeys或者使用 MySQL 函数
LAST_INSERT_ID()
。见http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html#connector-j-examples-autoincrement-select