0

In MySql, I want to use equivalent of SQL @@IDENTITY and I found this LAST_INSERT_ID(). I found in search that it work fines even if there are different sessions exist. I want to find last ID,in current session. I am using following code.

public static void main(String[] args) {

    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = null;
        conn = DriverManager.getConnection("jdbc:mysql://localhost/fuel","root", "");
        System.out.print("Database is connected !\n");

        Statement st = conn.createStatement();
        String response = "<food>";
        String insertQuery = "INSERT INTO transactions(user_input,fuel_response,execution_time)"+
                             "VALUES(?,?,?)";
        PreparedStatement prepareStatementObj = conn.prepareStatement(insertQuery);         
        prepareStatementObj.setString(1, "I drank a babyfood juice apple.");
        prepareStatementObj.setString(2, response);
        prepareStatementObj.setInt(3, 4500);            

        prepareStatementObj.execute();

        String queryForId = "SELECT LAST_INSERT_ID() FROM transactions";
        ResultSet rs2 = st.executeQuery(queryForId);
        if (!rs2.isBeforeFirst() ) {    
             System.out.println("No data"); 
        } else {
            while ( rs2.next() ) {
                int id = rs2.getInt("id");          
                System.out.println("Last id of this session was..."+id);
            }
        }

        conn.close();
    } catch(Exception e) {
        System.out.print("Do not connect to DB - Error:"+e);
    }
}

Code is working for Insertion but I am not getting last inserted id. It gives following exception.
Column 'id' not found. I will be thankful to you if you can help.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Hammad Hassan
  • 1,192
  • 17
  • 29

3 Answers3

2

Modify your select to use alias as id:-

SELECT LAST_INSERT_ID() as id FROM transactions
Rahul Yadav
  • 1,503
  • 8
  • 11
1

You're trying to grab a column called id, but there's no such column. When you grab the last inserted ID, you get a column called last_insert_id() instead:

MySQL> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                0 |
+------------------+
1 row in set (0.02 sec)

Easier to grab it by index (use .getInt(int)). This is perfectly safe because you know there will only be one column returned.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
1

You can use below code to get last insert id.

          ResultSet rs = prepareStatementObj.getGeneratedKeys();
            if(rs.next())
            {

                last_inserted_id=Integer.toString(rs.getInt(1));

            }
Rafiq
  • 740
  • 1
  • 5
  • 17