2013-11-25 63 views
0
SELECT ItemName, SUM(Unit) AS SoldUnit, SUM(Total) AS TotalAmount, 
     SUM(Profit) AS TotalProfit 
FROM InvoiceTable 
WHERE DateSO='"+dateTxt.getText()+"' 
GROUP BY ItemName; 

獲取訪問數據這是我的查詢,但我得到了如何通過日期在Java

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression. 

在訪問數據庫DateSoDate/Time型 請幫幫我。

+1

什麼是'dateTxt.getText()'的輸出? –

+0

瞭解預準備語句,並且不要使用字符串來表示日期。 –

回答

0

我建議你嘗試這樣

private static PreparedStatement prepareStatement(
    Connection conn, java.util.Date date) 
    throws SQLException { 
    final String sql = "SELECT ItemName, SUM(Unit) AS SoldUnit, " 
     + "SUM(Total) AS TotalAmount, " 
     + "SUM(Profit) AS TotalProfit " 
     + "FROM InvoiceTable WHERE DateSO=? GROUP BY ItemName"; 
    PreparedStatement ps = conn.prepareStatement(sql); 
    ps.setDate(1, new java.sql.Date(date.getTime())); 
    return ps; 
} 

然後用ResultSet rs = ps.executeQuery();,請務必在ResultSet始終clean up after yourself閱讀起來。

最後,如果你需要一個日期範圍(在你的SQL使用BETWEEN,並通過在兩個日期的對象)...

+0

捕捉異常並忽略它是您可以給新手的最糟糕的建議之一。讓你的方法拋出一個SQLException。 –