How to get last inserted id into jdbc in jsp

2019-09-08 18:34发布

问题:

How can I get ID from just inserted row in jsp?

        PreparedStatement ps = con.prepareStatement("INSERT INTO Recipients(CustomerID,Name, Street, City, ZipCode, PhoneNumber, EmailAddress,"
            + " ContactPersonName, ContactPersonSurname, ContactPersonPhoneNumber,ContactPersonEmailAddress) "
            + "values(?,?,?,?,?,?,?,?,?,?,?)");

And I need use id from Recipients to insert it into Parcels

PreparedStatement ps2 = con.prepareStatement("INSERT INTO Parcels(TransportTypeID,CustomerID,RecipientID,ParcelAmount, DimLength, DimHeight, DimWidth, ParcelWeigth, Content,"
            + " AdditionalDescription, IsCustomParcel, ReceiptFee, InsuranceAmount, OwnPick, DispatchDate) "
            + "values((?,?,?,?,?,?,?,?,?,?,?,?,?,?,?");

    ps2.setString(1,transportTypeID);
    ps2.setString(2,customerID);
    ps2.setInt(3,recipientID); ...

I was trying to use ResultSet:

int recipientID=0;
    ResultSet rs2=st.executeQuery("SELECT * FROM Recipients");
    if(rs2.last())
           {
            recipientID = rs2.getInt("RecipientID");
           }

but it didn't work.

回答1:

Try something like this:

String query = "BEGIN " +
               "  INSERT INTO Recipients( CustomerID, Name, Street, City, ZipCode, PhoneNumber" + 
               "                         ,EmailAddress, ContactPersonName, ContactPersonSurname" +
               "                         ,ContactPersonPhoneNumber, ContactPersonEmailAddress) " +
               "    VALUES(?,?,?,?,?,?,?,?,?,?,?) RETURNING id into ?; " +
               "END;";

CallableStatement cs = conn.prepareCall(query);

cs.setString(1,transportTypeID);
cs.setString(2,customerID);
cs.setInt(3,recipientID);
...
cs.registerOutParameter(12, java.sql.Types.INTEGER);

cs.execute();

int id = cs.getInt(12);

Then use the resultant id for your next insert. Or you could also put it all into a proc.



回答2:

I've found solution: ResultSet rs2=st.executeQuery("SELECT * FROM Recipients ORDER BY RecipientID DESC Limit 1;"); while(rs2.next()) { recipientID = rs2.getInt(1); }



标签: jsp jdbc insert