如何从jsp中插入的行中获取ID?
PreparedStatement ps = con.prepareStatement("INSERT INTO Recipients(CustomerID,Name, Street, City, ZipCode, PhoneNumber, EmailAddress,"
+ " ContactPersonName, ContactPersonSurname, ContactPersonPhoneNumber,ContactPersonEmailAddress) "
+ "values(?,?,?,?,?,?,?,?,?,?,?)");
我需要使用来自收件人的ID将其插入到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); ...
我试图使用ResultSet:
int recipientID=0;
ResultSet rs2=st.executeQuery("SELECT * FROM Recipients");
if(rs2.last())
{
recipientID = rs2.getInt("RecipientID");
}
但它不起作用。
答案 0 :(得分:2)
尝试这样的事情:
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进行下一次插入。或者你也可以将它全部放入过程中。
答案 1 :(得分:0)
我找到了解决方案:
ResultSet rs2=st.executeQuery("SELECT * FROM Recipients ORDER BY RecipientID DESC Limit 1;");
while(rs2.next())
{
recipientID = rs2.getInt(1);
}