2017-06-21 88 views
-1

我想使用日期選擇器來選擇日期範圍。日期的這個範圍,然後在其中求和計算數據庫中查詢...JavaFX MySQL數據庫返回金額

我嘗試:

public static int dateRange(){ 
    int value = 0; 

    PreparedStatement stmt = null; 
    try { 
     Connection connection = DriverManager.getConnection("", "", ""); 
     stmt = connection.prepareStatement("SELECT SUM(cost) FROM Items WHERE expiration_date between '" + Budget.datePicker1.getValue() + "' and '" + Budget.datePicker2.getValue() + "'"); 

     ResultSet result = stmt.executeQuery(); 
     result.next(); 
     String sum = result.getString(1); 
     value = Integer.parseInt(sum); 

    } catch (Exception e){ 
     value += 0; 
    } 
    return value; 
} 

它的工作原理。如果可以這麼說的話,它會返回總數。如果DatePicker中選擇的數據庫中沒有日期,那麼彈出0 ...但它看起來很糟糕(catch塊),我想知道是否有人可以幫助我選擇另一種解決方案嗎?

回答

1

首先,由於查詢返回的值是一個整數值,因此不需要將其作爲字符串讀取並解析它。只需使用result.getInt(...)即可。

其次,如果您打算使用PreparedStatement,請使用它來正確設置參數,而不是使用連接字符串構建查詢。做後者將您的應用程序暴露給SQL injection attacks

如果沒有您的日期在範圍內,那麼SQL查詢將返回NULL。在will return 0結果集的列上調用getInt(),所以無論如何你都會得到你想要的結果。如果從結果集中獲得的前一個值爲SQL NULL,則調用result.wasNull()將返回true,因此如果您確實需要分別處理該情況,則可以使用該機制來執行此操作。

你可以這樣做:

public static int dateRange(){ 
    int value = 0; 

    // Use try-with-resources to make sure resources are released: 
    try (
     Connection connection = DriverManager.getConnection("", "", ""); 
     PreparedStatement stmt = connection.prepareStatement(
      "SELECT SUM(cost) FROM Items WHERE expiration_date between ? and ?"); 
    ) { 

     stmt.setDate(1, Date.valueOf(Budget.datePicker1.getValue())); 
     stmt.setDate(2, Date.valueOf(Budget.datePicker2.getValue())); 
     ResultSet result = stmt.executeQuery(); 
     result.next(); 

     // Note that if there are no values in range, the SQL result will be NULL 
     // and getInt() will return 0 anyway. 
     value = result.getInt(1); 

     // however, if you need to explicitly check this and do something different 
     // if nothing is in range, do: 
     if (result.wasNull()) { 
      // nothing was in range... 
     } 

    } catch (SQLException e){ 
     // this actually indicates something went wrong. Handle it properly. 
     Logger.getGlobal().log(Level.SEVERE, "Error accessing database", e); 
     // inform user there was a db error, etc... 
    } 
    return value; 
} 
+0

謝謝,我有許多問題和使用JavaFX /數據庫過去一週的問題,似乎像你的人。給你很大的榮譽! – purpleman