2015-05-12 54 views
0

什麼是正確的方法,所以我可以查詢此聲明,其中來自jdatechooser的日期將是我的參數jdatechooser作爲參數在MySQL查詢

DefaultTableModel model= (DefaultTableModel)DisplayRecieveTB.getModel(); 
     DisplayRecieveTB.revalidate(); 
     model.getDataVector().removeAllElements(); 

     try{ 

      String date = DateChooserRS.getDate().toString(); 

     stmt = conn.createStatement(); 
    stmt.executeQuery("SELECT *FROM supplyrecievable where recievedate = '"+date+"' "); 
    rs = stmt.getResultSet(); 
     while (rs.next()) 
     { 
        String r1 = rs.getString("itemname"); 
        String r2 = rs.getString("itemgroup"); 
        String r3 = rs.getString("itemcount"); 
        String r4 = rs.getString("totalcost"); 
        String r5 = rs.getString("itemcode"); 
        model.addRow(new Object[] {r5,r1,r2,r3,r4}); 
        DisplayRecieveTB.revalidate(); 

     } 
     } 
     catch(Exception e) 
     { 
      JOptionPane.showMessageDialog(null, e.getMessage()); 
     } 

回答

1
  1. 使用PreparedStatement
  2. 不要轉換Date值到String,結果值很可能是不相容的(並且如果數據庫列是除日期或時間戳類型之外的任何其他東西,那麼您做錯了)

例如...

DefaultTableModel model = (DefaultTableModel) DisplayRecieveTB.getModel(); 
DisplayRecieveTB.revalidate(); 
model.getDataVector().removeAllElements(); 

try { 

    Date date = DateChooserRS.getDate(); 

    try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM supplyrecievable where recievedate = ?")) { 
     // You can also use a java.sql.Timestamp if the column is of the correct type 
     stmt.setDate(1, new java.sql.Date(date.getTime())); 
     try (ResultSet rs = stmt.executeQuery()) { 
      while (rs.next()) { 
       String r1 = rs.getString("itemname"); 
       String r2 = rs.getString("itemgroup"); 
       String r3 = rs.getString("itemcount"); 
       String r4 = rs.getString("totalcost"); 
       String r5 = rs.getString("itemcode"); 
       model.addRow(new Object[]{r5, r1, r2, r3, r4}); 
       // This is pointless, as the model should notifty the table it needs to be updated 
       //DisplayRecieveTB.revalidate(); 

      } 
     } 
    } 
} catch (Exception e) { 
    JOptionPane.showMessageDialog(null, e.getMessage()); 
} 

這是假定數據庫列類型與java.sql.Date值兼容

Using Prepared Statements更多細節

+0

謝謝主席先生:) – Pyne