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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:16:41  来源:igfitidea点击:

Returning generated keys in MySql with JDBC PreparedStatement

javajdbcdao

提问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_INCREMENTcolumn in MySQL. The current implementation has no problems. But I would like to know the value that was generated in the AUTO_INCREMENTcolumn.

我用普通的编程JDBC一个DAO层,因为我只有 61.38 MBJava内存在我的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.

我很感激你的帮助。