获取插入行的ID

时间:2015-06-18 17:37:38

标签: java jdbc

我正在尝试获取插入行的 $(document).ready(function() { $('.tooltip').each(function(){ $(this).tooltipster({ content: $(''+$(this).attr('title')+' people played this game') }); }); }); 。 Currenly我没有得到id,我得到异常id但是当我在评论代码中查询它时,我得到它,但它是java.sql.SQLException: Column 'route_id' not found.中的所有行表。我该如何解决?

我感谢任何帮助。

代码:

routes

路线表:

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);
        }

    }
}

1 个答案:

答案 0 :(得分:1)

这可能会对您有所帮助 -

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()会返回整个架构中任何表中最后插入的id。请确保此方法是原子的,并且在此方法完全执行时不会插入任何其他人。

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

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