我正在尝试获取 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 中使用什么以及参数..
使用 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);
尝试使用别名
rs = st.executeQuery("select last_insert_id() as last_id from schedule");
lastid = rs.getString("last_id");
请参阅此帖子以获取答案和解释
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getInt(1);
}
为什么不
SELECT MAX(id) FROM schedule
如果 id 您的列的名称不同于id
,则需要在上述查询中相应地替换它。
你可以像这样使用它:
rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
int lastid = rs.getInt("id");
您可以使用以下查询来获取最后插入行的最后一个 auto_incremented ID。
SELECT (max(auto_incr_id)) from table_name;
另外一个选项:
SELECT id FROM table_name ORDER BY id DESC LIMIT 1;