Java JDBC - get the last inserted id

Java JDBC - get the last inserted id after an object creation

In order to get the last inserted id, we'll use the function getGeneratedKeys of prepared statement object which return a ResultSet that will be iterated in order to get our last inserted id.

import java.sql.*;

public class LastInsertedId {

    public static void main(String[] args) {
        Connection c = null;
        try{
            Class.forName("jdcb driver name");
            c = DriverManager.getConnection("connection information","username", "password");

            //insert data and get the inserted id
            String createQuery= "insert into User('name') values (?)";
            PreparedStatement preparedStatement = c.prepareStatement(createQuery, Statement.RETURN_GENERATED_KEYS);
            preparedStatement.setString(1, "yamicode" + Math.random());
            preparedStatement.executeUpdate();
            Long id = null;
            if (rs.next()){
                id = rs.getLong(1);
            }
            System.out.println("The generated id is: " + id);
            preparedStatement.close();

        }catch(Exception e){
            System.out.println(e);
        }
        if(c!=null){
            try {
                c.close();
            }catch (Exception e){
                System.out.println(e);
            }
        }
    }
}