我想从数据库中的表中检索最后一个主键插入(ID)的记录,这是我的程序的样子,但是当我运行它时将返回到空白页面。查询错了吗?
<div style="background:steelblue;">
<form action=saveRecord.jsp> <<----will save the record to other table
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dssps", "root", "admin");
String query = "select Did,ShipName,Origin,Port1 from decsfinal where Did=LAST_INSERT_ID()";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
if(rs.next()){
%>
<label>ID</label>
<input name="Did" value="<%=rs.getInt("Did")%>">
</br>
<label>Ship Name</label>
<input name="ShipName" value="<%=rs.getString("ShipName")%>">
</br>
<label>Origin Port</label>
<input name="Origin" value="<%=rs.getString("Origin")%>">
</br>
<label>Destination Port</label>
<input name="Port1" value="<%=rs.getString("Port1")%>">
</br>
// here the submit button and close database
答案 0 :(得分:0)
您可以使用:
<div style="background:steelblue;">
<form action=saveRecord.jsp>
<%
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dssps", "root", "admin");
String query = "select Did, ShipName, Origin, Port1 from decsfinal where Did = LAST_INSERT_ID()";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
if (rs.next()) {
out.print(rs.getInt(1));
out.print(rs.getString(2));
out.print(rs.getString(3));
out.print(rs.getString(4));
//Or you can use
// out.print(rs.getInt("Did"));
// out.print(rs.getString("ShipName"));
// out.print(rs.getString("Origin"));
// out.print(rs.getString("Port1"));
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</form>
</div>
答案 1 :(得分:-1)
last_insert_id()方法正在检索last_id + 1表示如果你的最后一个id是9它正在检索10并在where子句中进行比较,因此没有id等于10你的查询正在检索null,试试这个查询(对我有用)。
select Did,ShipName,Origin,Port1 from decsfinal where Did = Last_insert_id()-1;
OR 如果您的主键(Did)设置为自动增量,则可以使用此查询来获得所需的结果
select max(Did) , ShipName ,Origin,Port1 from decsfinal;