小编典典

如何在jsp中将最后插入的id获取到jdbc

jsp

我如何从jsp中插入的行中获取ID?

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

我需要使用收件人的ID将其插入包裹

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); ...

我正在尝试使用ResultSet:

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

但这没用。


阅读 208

收藏
2020-06-10

共1个答案

小编典典

尝试这样的事情:

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);

然后将结果ID用于下一个插入。或者您也可以将其全部放入proc中。

2020-06-10