我使用普通JDBC和DAO图层进行编程,因为我的 Tomcat中的 Java内存上只有 61.38 MB (服务托管)。我在MySQL中有一个包含AUTO_INCREMENT
列的表。目前的实施没有问题。但我想知道AUTO_INCREMENT
列中生成的值。
当前代码在插入新行的方法中如下所示。
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 {
...
}
}
我已经看到这可以在 Hibernate
中使用,但因为我的内存很少,所以不是一个可行的选择。
我很感激帮助。
答案 0 :(得分:5)
有两种方法:
使用getGeneratedKeys()
的JDBC概念。请参阅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