获取在mysql中最后插入的自动增量id

时间:2022-09-25 15:34:43

I am trying to get the mysql command like mysql_insert_id(); which retrieve the last inserted row's auto_increment id. What can I do to get it in Java?

我正在尝试获取mysql命令,比如mysql_insert_id();它检索最后插入的行的auto_increment id。我可以做什么才能在Java中获取它?

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

my lastid was declared as INT. I dono what to use in rs.get and also the parameter..

我的lastid被声明为INT.我不知道在rs.get和参数中使用什么。

5 个解决方案

#1


21  

Try using an alias

试着用一个别名

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

#2


24  

Using JDBC, you can use Connection.PreparedStatement(query, int) method.

使用JDBC,您可以使用连接。PreparedStatement(查询,int)方法。

PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);  
pstmt.executeUpdate();  
ResultSet keys = pstmt.getGeneratedKeys();    
keys.next();  
key = keys.getInt(1);

#3


6  

see this post for answer & explanation

答案和解释请看这篇文章

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

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getInt(1);
}

#4


4  

Why not

为什么不

SELECT MAX(id) FROM schedule

If id your column has a different name than id, you need to replace it accordingly in the above query.

如果您的列具有与id不同的名称,您需要在上面的查询中相应地替换它。

You can use it like:

你可以这样使用:

rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
int lastid = rs.getInt("id");

#5


0  

You can use following query to get last auto_incremented ID of last inserted row.

您可以使用以下查询获取最后插入行的auto_increment ID。

SELECT (max(auto_incr_id)) from table_name;

#1


21  

Try using an alias

试着用一个别名

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

#2


24  

Using JDBC, you can use Connection.PreparedStatement(query, int) method.

使用JDBC,您可以使用连接。PreparedStatement(查询,int)方法。

PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);  
pstmt.executeUpdate();  
ResultSet keys = pstmt.getGeneratedKeys();    
keys.next();  
key = keys.getInt(1);

#3


6  

see this post for answer & explanation

答案和解释请看这篇文章

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

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getInt(1);
}

#4


4  

Why not

为什么不

SELECT MAX(id) FROM schedule

If id your column has a different name than id, you need to replace it accordingly in the above query.

如果您的列具有与id不同的名称,您需要在上面的查询中相应地替换它。

You can use it like:

你可以这样使用:

rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
int lastid = rs.getInt("id");

#5


0  

You can use following query to get last auto_incremented ID of last inserted row.

您可以使用以下查询获取最后插入行的auto_increment ID。

SELECT (max(auto_incr_id)) from table_name;