0

I have read the main article for getting the last inserted ID in MySQL using jdbc in java but I could not seem to get it right.

    int identity;

    public void insertdata(){

     Connection con = Connect();
     Statement statement;
     statement = (Statement) con.createStatement();
     String sql = "INSERT INTO table1 (Surname, FirstName, MiddleName, Birthday)" + " VALUES('"+surname+"', '"+fName+"', '"+mName+"', '"+bDay+"');";
    statement.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = statement.getGeneratedKeys();
    rs.next();
    identity=rs.getInt(1);
    statement.close();
    con.close();


}
  • Please format your code properly and avoid overlong lines of code. – Turing85 Oct 31 '17 at 20:31
  • And what is happening? – Antoniossss Oct 31 '17 at 20:34
  • @Antoniossss yes. read that already. what happened is that the value of my identity is possibly 0. I say possible because the default value of the column that I wanted to insert the identity in to is 0. the identity always returns 0. – NoobProgrammer Oct 31 '17 at 20:44
  • And why it is 0? if it is primary key then it shoul have no default value, and be unique across whole table, possibly auto-incremented. So basicly 0 is the response you should expect, as this is the last insert id(you are not setting this id in your query so it gets default) – Antoniossss Oct 31 '17 at 20:47
  • You need to have autoincrement primary key on your table1 – Antoniossss Oct 31 '17 at 20:48
  • Yes I have an auto-incremented key from my table1. I needed to pass the last auto-incremented key to the identity variable and then insert it to table2. – NoobProgrammer Oct 31 '17 at 20:53
  • table 2 has the column(where I wanted to insert the identity) with a default value of 0. – NoobProgrammer Oct 31 '17 at 20:57
  • please post the entire code(where this method is called and how you get this value into your next query) – isaace Oct 31 '17 at 21:04
  • I have solved my own problem. Turns out, I called the method in a separate class instance. – NoobProgrammer Oct 31 '17 at 21:18

0 Answers0