16

我正在尝试获取 mysql_insert_id(); 之类的 mysql 命令;它检索最后插入的行的 auto_increment id。我该怎么做才能在 Java 中获得它?

rs = st.executeQuery("select last_insert_id() from schedule");
lastid = rs.getString("last_insert_id()");

我的lastid被宣布为INT。我不知道在 rs.get 中使用什么以及参数..

4

6 回答 6

29

使用 JDBC,您可以使用Connection.PreparedStatement(query, int)方法。

PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);  
pstmt.executeUpdate();  
ResultSet keys = pstmt.getGeneratedKeys();    
keys.next();  
key = keys.getInt(1);
于 2013-01-05T10:04:54.490 回答
25

尝试使用别名

rs = st.executeQuery("select last_insert_id() as last_id from schedule");
lastid = rs.getString("last_id");
于 2013-01-05T10:00:13.500 回答
7

请参阅帖子以获取答案和解释

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getInt(1);
}
于 2013-06-18T12:16:10.823 回答
3

为什么不

SELECT MAX(id) FROM schedule

如果 id 您的列的名称不同于id,则需要在上述查询中相应地替换它。

你可以像这样使用它:

rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
int lastid = rs.getInt("id");
于 2013-01-05T10:01:09.013 回答
0

您可以使用以下查询来获取最后插入行的最后一个 auto_incremented ID。

SELECT (max(auto_incr_id)) from table_name;
于 2018-01-16T11:54:57.490 回答
0

另外一个选项:

SELECT id FROM table_name ORDER BY id DESC LIMIT 1;

于 2020-08-16T03:57:13.240 回答