获取插入行的id

Get the id of the inserted row

我正在尝试获取插入行的 id。目前我没有得到 id 并且我得到异常 java.sql.SQLException: Column 'route_id' not found. 但是当我在注释代码中查询它时我得到它但是它是 routes 中的所有行table。我该如何解决?

感谢任何帮助。

代码:

if (routesTables.next()) {

    PreparedStatement prepRoutesInsert = con.prepareStatement(
            "INSERT INTO routes(direction, route)"
                    + "VALUES( ?, ?)",
            Statement.RETURN_GENERATED_KEYS);

    prepRoutesInsert.setString(1, direction);
    prepRoutesInsert.setInt(2, route);

    prepRoutesInsert.executeUpdate();

    // PreparedStatement prepRoutesInsert2 =
    // con.prepareStatement(
    // "SELECT route_id from routes");
    // ResultSet rs = prepRoutesInsert2.executeQuery();
    // while(rs.next()){
    // int route_id2 = rs.getInt("route_id");
    // System.out.println(route_id2);
    // }

    try (ResultSet generatedKeys = prepRoutesInsert
            .getGeneratedKeys()) {
        if (generatedKeys.next()) {
            int id = generatedKeys.getInt("route_id");
            System.out.println("The id is: " + id);
        }

    }
}

路线table:

stt.execute("CREATE TABLE IF NOT EXISTS routes ("
                + "route_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
                + "direction VARCHAR(30) NOT NULL, "
                + "route INT(11) NOT NULL )");

这可能对您有所帮助 -

public static int insertInDB(String sqlQuery) {
        Connection conn = getDBConnection();
        ResultSet rs = null;
        int id = 0;
        try {
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            stmt.executeUpdate(sqlQuery);
            Statement stmt1 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = stmt1.executeQuery("select last_insert_id()");
            while(rs.next()){
                id = rs.getInt(1);
            }
        } catch (Exception e) {
            closeDBConnection();
        }
        return id;
    }

请记住,last_insert_id() returns 最后在整个架构中的任何表中插入了 id。请确保此方法是原子的,并且在此方法完全执行时没有其他人插入。

请阅读此 - https://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

之前的讨论可能会有所帮助 - LAST_INSERT_ID() MySQL