Search code examples
javamysqllast-insert-id

Get last id from MySQL


I'm trying to get the last ID from MySQL and assign the value to string a.

I have a table admin with a adminID column.

 adminAPI api= new adminAPI();
                 try {
                    String id= api.selectLastID();
                    System.out.println(id);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

adminAPI

public String selectLastID() throws Exception  
    {
    String a;
    String sql="Select last_insert_id() as adminID from admin";
    DatabaseConnection db = new DatabaseConnection();
    Connection  conn =db.getConnection();
    PreparedStatement  ps = conn.prepareStatement(sql);
     ResultSet rs = ps.executeQuery();
     while(rs.next()) 
     {  
          a= rs.getString("adminID");
         System.out.println(a);
     }
     ps.close();
     rs.close();
     conn.close();
     return null ;
 }

I suppose to get 1 since I have one ID in admin table.

Here the output I get

0
null

Thanks.

DatabaseConnection

package database;
import java.sql.Connection;
import java.sql.DriverManager;

public class DatabaseConnection {
     String driver;
     String dbName;
     String connectionURL;

     String username;
     String password;
     public DatabaseConnection()
     {
         driver = "com.mysql.jdbc.Driver";
         connectionURL = "jdbc:mysql://localhost/";
         dbName = "user";
         username = "root";
         password = "";
     }

     public Connection getConnection() throws Exception {

          Class.forName(driver);
          Connection connection = DriverManager.getConnection(connectionURL+dbName,username,password);

          return connection;
     }

     public static void main(String[] args) {
         DatabaseConnection db = new DatabaseConnection();
            try {
                Connection conn = db.getConnection();
                System.out.println("Database successfully connected!");
                conn.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
}

Solution

  • You can not get the last inserted, but you can get the greatest (I think is what you need):

    Select max(columnId) as adminID from admin
    

    Where 'id' is replaced with the name of the colum you are trying to get

    You ususally use an id that increases, so the last id you have inserted is the greatest.