Get last inserted auto increment id in mysql

前端 未结 6 830
你的背包
你的背包 2020-12-09 10:10

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?

rs =         


        
相关标签:
6条回答
  • 2020-12-09 10:54

    Try using an alias

    rs = st.executeQuery("select last_insert_id() as last_id from schedule");
    lastid = rs.getString("last_id");
    
    0 讨论(0)
  • 2020-12-09 10:54

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

    PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);  
    pstmt.executeUpdate();  
    ResultSet keys = pstmt.getGeneratedKeys();    
    keys.next();  
    key = keys.getInt(1);
    
    0 讨论(0)
  • 2020-12-09 11:04

    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);
    }
    
    0 讨论(0)
  • 2020-12-09 11:05

    Another option:

    SELECT id FROM table_name ORDER BY id DESC LIMIT 1;

    0 讨论(0)
  • 2020-12-09 11:12

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

    SELECT (max(auto_incr_id)) from table_name;
    
    0 讨论(0)
  • 2020-12-09 11:15

    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.

    You can use it like:

    rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
    int lastid = rs.getInt("id");
    
    0 讨论(0)
提交回复
热议问题