简体   繁体   中英

How do I insert last_insert_id using preparedStatement?

I am facing difficulty in inserting " last_insert_id" in my prepared statement.I got how to select the last_insert_id in prepared statement like below:

PreparedStatement getLastInsertId = con.prepareStatement("SELECT LAST_INSERT_ID()");

When I use the same procedure for inserting last_insert_id in my preparedstatement like this:

1.  PreparedStatement pst =  con.prepareStatement("insert into introducer_table  values(?,?,?,?)");
2.     
3.     //introducer details into database
4.       pst.setString(1,LAST_INSERT_ID());
5.     pst.setString(2, nameofintroducer);
6.     pst.setString(3, accountno);
7.     pst.setString(4, signofintroducer);

Im getting 'null' value in the first column.can any one help me to come out from this problem

If your doing both the save actions at a time use getGeneratedKeys() , It's pretty much java.

I'm not a SQL guru, but here I found a way to get the generated id using getGeneratedKeys()

    long generatedId= 0L;
    statement = con
            .getConnection()
            .prepareStatement(
                    "insert into  new_user set name= ? , contact= ? , ....",
                    statement.RETURN_GENERATED_KEYS);
    statement.setString(1, "examplename");
    statement.setString(2, "examplecontact");
    ------
    statement.executeUpdate();
    ResultSet generatedKeys = statement.getGeneratedKeys();
    if (generatedKeys.next()) {
        generatedId = generatedKeys.getLong(1);// here is your generated Id , use it to  insert in your introducer_table
    }

     PreparedStatement pst =  con.prepareStatement("insert into introducer_table  values(?,?,?,?)");

         //introducer details into database
         pst.setString(1, generatedId);
         pst.setString(2, nameofintroducer);
         pst.setString(3, accountno);
         pst.setString(4, signofintroducer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM