2017-06-21 13 views
-1

datepickerを使用して日付の範囲を選択したいと考えています。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がポップアップします...しかし、それは(ブロックをキャッチして)混乱しているように見えます。誰かが代替ソリューションを手伝ってくれるかどうか疑問に思っていましたか?

答えて

1

最初に、クエリによって返される値は整数値なので、文字列として読み取って解析する必要はありません。ちょうどresult.getInt(...)を使用してください。

第2に、PreparedStatementを使用する場合、それを使用して、連結文字列からクエリを構築するのではなく、パラメータを適切に設定します。後者を実行すると、アプリケーションがSQL injection attacksに公開されます。

日付が範囲内にない場合、SQLクエリはNULLを返します。 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