2017-08-20 68 views
0

我想用一個過濾器按日期來選擇從一個數據庫表中的一些數據(日期列是:[searchDate] DATETIME DEFAULT CURRENT_TIMESTAMP,)使用日期篩選器從SQLite中選擇一些數據?

在該PIC中,我使用的SQLite專家和按日期的過濾器: enter image description here

這個代碼是獲取當前年份和月份:

DateFormat YEAR_FORMAT = new SimpleDateFormat("yyyy"); 
     DateFormat MONTH_FORMAT = new SimpleDateFormat("MM"); 
     YEAR_DATE = YEAR_FORMAT.format(new Date()); 
     MONTH_DATE = MONTH_FORMAT.format(new Date()); 
     Date date = new Date(); 
     Log.d("Month", YEAR_FORMAT.format(date) + " " + MONTH_FORMAT.format(date)); 

,並在我的應用程序光標查詢獲得通過日期過濾列表(當年):

public List<Moment> MOMENT_YEAR(String year) { 
     try { 
      Moment MOMENT_TABLE; 
      List<Moment> MOMENTS = new ArrayList<>(); 
      DB_HELPER.openDatabase(); 
      db.beginTransaction(); 
      Cursor MOMENT_CURSOR = db.rawQuery("SELECT * FROM tblMoment WHERE strftime('%Y', searchDate) =" + year, null); 
      db.setTransactionSuccessful(); 
      MOMENT_CURSOR.moveToFirst(); 
      while (!MOMENT_CURSOR.isAfterLast()) { 
       MOMENT_TABLE = new Moment(MOMENT_CURSOR.getInt(0), MOMENT_CURSOR.getString(1), MOMENT_CURSOR.getString(2), MOMENT_CURSOR.getString(3), 
         MOMENT_CURSOR.getString(4), MOMENT_CURSOR.getString(5), MOMENT_CURSOR.getInt(6), MOMENT_CURSOR.getInt(7) != 0); 
       MOMENTS.add(MOMENT_TABLE); 
       MOMENT_CURSOR.moveToNext(); 
      } 
      MOMENT_CURSOR.close(); 
      return MOMENTS; 
     } catch (Exception e) { 
      return null; 
     } finally { 
      db.endTransaction(); 
      DB_HELPER.closeDatabase(); 
     } 
    } 

我試過了,但沒有任何反應,列表爲空(空)。
我今年的日期最多。

回答

1

難道不清楚嗎?在查詢中用SQL字符串分隔符(')環繞year變量。

Cursor MOMENT_CURSOR = 
    db.rawQuery("SELECT * FROM tblMoment WHERE strftime('%Y', searchDate) = '" + year + "'", null); 

或者只是使用參數查詢(字符串分隔符將由Android爲您處理)。

Cursor MOMENT_CURSOR = 
    db.rawQuery("SELECT * FROM tblMoment WHERE strftime('%Y', searchDate) = ?", new String[]{year}); 
相關問題