I want to retrieve a record from a table in database base on last primary key insert(the ID), this how my program looks like, but when i run it'll return to blank page. Is the query wrong??
<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
You can use this :
<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>
last_insert_id() method is retrieving last_id+1 means if you have last id as 9 it is retrieving 10 and comparing it in the where clause, hence there is no id which is equal to 10 your query is retrieving null, try this query(it worked for me).
select Did,ShipName,Origin,Port1 from decsfinal where Did = Last_insert_id()-1;
OR if your primary key(Did) is set to auto increment you can use this query to get result you want
select max(Did) , ShipName ,Origin,Port1 from decsfinal;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.