如何在jsp中将最后插入的id获取到jdbc中 [英] How to get last inserted id into jdbc in jsp
本文介绍了如何在jsp中将最后插入的id获取到jdbc中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从jsp中刚刚插入的行中获取ID?
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(?,?,?,?,?,?,?,?,?,?,?)");
我需要使用收件人的ID将其插入包裹中
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); ...
我正在尝试使用ResultSet:
I was trying to use ResultSet:
int recipientID=0;
ResultSet rs2=st.executeQuery("SELECT * FROM Recipients");
if(rs2.last())
{
recipientID = rs2.getInt("RecipientID");
}
但是没有用.
推荐答案
尝试如下操作:
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.
Then use the resultant id for your next insert. Or you could also put it all into a proc.
这篇关于如何在jsp中将最后插入的id获取到jdbc中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文