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.