简体   繁体   中英

get entries with todays date

I am trying to get all the rows with today's date, and return the number of rows I get. The app crashes when it loads.

Method/SQLite query

 public int getTodaysCount() {
    SQLiteDatabase db = smokinDBOpenHelper.getWritableDatabase();
    GregorianCalendar gc = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String today = sdf.format(gc.getTime());

    Cursor cursor = db.rawQuery("SELECT * FROM " + smokinDBOpenHelper.INCIDENTS_TABLE
            + " WHERE " + KEY_DATE + " = DATETIME( ' " + today + " ' )", null);


    if (cursor.getCount() == 0 || !cursor.moveToFirst()) {

        throw new SQLException("No entries found");
    }

    return cursor.getCount();       
}

Error from log

03-20 12:26:25.913: E/AndroidRuntime(677): Caused by: 
android.database.sqlite.SQLiteException: near "==": syntax error (code 1): , while 
compiling: SELECT * FROM incidentsWHERE DATE_COLUMN == DATETIME( ' 2013-03-20 ' )

The error log seems to be telling me I'm not allowed to use the == . So if that's the case how do I perform this operation? With <= and >= ? Also is there a way to perform this query as a regular query as in not rawQuery ?

Example:

db.query(SmokinDBOpenHelper.INCIDENTS_TABLE, new String[] 
            {KEY_ID, KEY_DATE}, KEY_DATE.equals(now) , null, null, null, null);

Edit

New Log error message:

03-20 12:56:22.103: E/AndroidRuntime(1153): Caused by:    
android.database.sqlite.SQLiteException: no such column: DATE_COLUMN (code 1): , while 
compiling: SELECT * FROM incidents WHERE DATE_COLUMN = DATETIME( ' 2013-03-20 ' )

Incidents Table

public static final String KEY_ID = "_id";

public static final String KEY_LOCATION = "location";
public static final int LOCATION_COLUMN = 1;

public static final String KEY_DATE = "date";
public static final int DATE_COLUMN = 2;

private SmokinDBOpenHelper smokinDBOpenHelper;

public MySmokinDatabase (Context context) {
    smokinDBOpenHelper = new SmokinDBOpenHelper(context, SmokinDBOpenHelper.DATABASE_NAME, 
            null, SmokinDBOpenHelper.DATABASE_VERSION);
}   

private static class SmokinDBOpenHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "smokin.db";
    private static final String INCIDENTS_TABLE = "incidents";
    private static final int DATABASE_VERSION = 1;

    //SQL Statement to create a new database.

    private static final String DATABASE_CREATE = "create table " + 
        INCIDENTS_TABLE + " (" + 
        KEY_ID +  " integer primary key autoincrement, " +
        KEY_LOCATION + " text not null, " + 
        KEY_DATE + " text not null);";

    // Constructor

    public SmokinDBOpenHelper(Context context, String name, 
                   CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    //Called when no database exists in disk and the helper class needs
    //to create a new one. 

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE);
    }

    //Called when there is a database version mismatch meaning that the version
    //of the database on disk needs to be upgraded to the current version.

    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
        // Log the version upgrade.
        Log.w("TaskDBAdapter", "Upgrading from version " + 
                              _oldVersion + " to " +
                              _newVersion + ", which will destroy all old data");

        // Upgrade the existing database to conform to the new version. Multiple 
        // previous versions can be handled by comparing _oldVersion and _newVersion
        // values.

        // The simplest case is to drop the old table and create a new one.
        _db.execSQL("DROP TABLE IF EXISTS " + INCIDENTS_TABLE);
        // Create a new one.
        onCreate(_db);
    }       
}

Latest Error Message

03-20 13:33:03.483: E/AndroidRuntime(1342): Caused by: android.database.SQLException: 
No entries found

Insert Methods

public void smokedHandler(View view) {
    Spinner spinner = (Spinner) findViewById(R.id.location_spinner);

    String s = spinner.getSelectedItem().toString();
    String d = model.getDates();

    mySmokinDatabase.insertSmokinValues(s, d);      

    refreshView();
}

public long insertSmokinValues(String s, String d) {
    SQLiteDatabase db = smokinDBOpenHelper.getWritableDatabase();
    ContentValues newSmokinValues = new ContentValues();

    newSmokinValues.put(KEY_DATE, s);
    newSmokinValues.put(KEY_LOCATION, d);

    return db.insert(SmokinDBOpenHelper.INCIDENTS_TABLE, null, newSmokinValues);
}

public String getDates() {
    GregorianCalendar gc = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    dates = sdf.format(gc.getTime());       

    return dates;
}

last note is that the values being stored in my database when i click the button right now are
s: Home
d: 2013-3-20 - 14:09

As always thanks for any help!

android.database.sqlite.SQLiteException: near "==": syntax error (code 1)

Your logcat says everything. Problem is == this is operator that returns boolean value and you need association.

String query = "SELECT * FROM " + smokinDBOpenHelper.INCIDENTS_TABLE
+ " WHERE DATE_COLUMN = DATETIME( ' " + today + " ' )", null);

Note:

I recommend you to use placeholders instead of your hardcoded approach. It's cleaner and safer and you avoid problems what you forgot single quotes.

Cursor c = db.rawQuery(query, new String[] {today});

Update:

android.database.sqlite.SQLiteException: no such column: DATE_COLUMN (code 1):

This means that your DATE_COLUMN not exist in your database. You defined it with constant KEY_DATE so you need change query into:

String query = "SELECT * FROM " + smokinDBOpenHelper.INCIDENTS_TABLE
    + " WHERE " + KEY_DATE + " = DATETIME( ' " + today + " ' )", null);

Update 2:

My suggestion is to perform simple query without where clause and you will see if you have records in db:

String query = "SELECT * FROM " + smokinDBOpenHelper.INCIDENTS_TABLE", null);

Use '=' sign instead of '==' sign as Sqlite does not support '==' sign in Query statement. eg:

    Cursor cursor = db.rawQuery(
        "SELECT * FROM "
        + smokinDBOpenHelper.INCIDENTS_TABLE +
        " WHERE " + 
        "DATE_COLUMN = DATETIME( ' " + today + " ' )", null);

You are lacking a space between incidents and WHERE :

Cursor cursor = db.rawQuery(
            "SELECT * FROM "
            + smokinDBOpenHelper.INCIDENTS_TABLE +
            " WHERE " + 
            "DATE_COLUMN = DATETIME( ' " + today + " ' )", null);

Notice the space added before WHERE .

Also == should be a single =

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM