2017-04-10 55 views
1

我想從基於最後主鍵插入(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

您可以使用此:

<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> 
+0

因此它會得到的最後數據主要在表中? –

+0

YES @한나강'LAST_INSERT_ID()'將檢索最後一個ID –

+0

我試圖改變「到」,但它不工作,我得到錯誤 –

-1

LAST_INSERT_ID()方法檢索last_id + 1只意味着如果你有最後一個ID爲9被檢索10,並在where子句中進行比較,因此存在是沒有ID等於10您的查詢正在檢索空,請嘗試此查詢(它爲我工作)。

select Did,ShipName,Origin,Port1 from decsfinal where Did = Last_insert_id()-1;

或 如果你的主鍵(DID)設置爲自動增量您可以使用此查詢來獲取引起你想

select max(Did) , ShipName ,Origin,Port1 from decsfinal;

相關問題