如何从逗号分隔数据库中获取数据?

时间:2014-03-23 20:41:56

标签: java android sql database sqlite

我创建了两个表:

attendance_data

CREATE TABLE attendance_data 
(  
  _id integer primary key autoincrement,
  stud_roll text not null,
  sem integer ,
  class_id integer 
);

class_data

CREATE TABLE class_data 
( 
  class_id integer primary key autoincrement, 
  course_name text not null, 
  t_id integer, 
  date text 
);

我想从class_id表中获取class_data,其中date列的值为currtime,即2014年3月24日上午1:41:12 < / p>

但是在查询时显示以下错误:

03-24 01:41:12.194: I/SHUBH(2245): GETTING Class ID by Mar 24, 2014 1:41:12 AM
03-24 01:41:12.194: I/Database(2245): sqlite returned: error code = 1, msg = near "24": syntax error
03-24 01:41:12.214: W/System.err(2245): android.database.sqlite.SQLiteException: near "24": syntax error: , while compiling: SELECT DISTINCT class_id FROM class_data WHERE date = Mar 24, 2014 1:41:12 AM
03-24 01:41:12.214: W/System.err(2245):     at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
03-24 01:41:12.224: W/System.err(2245):     at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)

我认为这是因为日期中出现的逗号。我该如何编写查询以使其工作?

这是我为获取ID而编写的 getClassID()方法:

public String getClassID(String currtime) {

    // TODO Auto-generated method stub
    String cidddd = "";
    Log.i("SHUBH", "GETTING Class ID by " + currtime);

    Cursor mCursor = mDb.query(
                        true, 
                        DATABASE_TABLE5,
                        new String[] { KEY_CLASS_ID }, 
                        " date " + " = " + currtime,
                        null, null, null, null, null);

    if (mCursor != null) {

        startManagingCursor(mCursor);

        while (mCursor.moveToNext()) {
            cidddd = mCursor.getString(0);
        }

        System.out.println(cidddd + "This is the class IDDDDDDDDDDDDDDDDDDDDDD");
        mCursor.close();            
    }

    System.out.println("Cursor NuLL");
    return cidddd;
}

1 个答案:

答案 0 :(得分:0)

currtime日期字符串中的文字用单引号括起来将超出语法错误:

SELECT DISTINCT class_id FROM class_data WHERE date = 'Mar 24, 2014 1:41:12 AM'

因此,将getClassID()方法中的第8行更改为:

" date = '" + currtime + "'", 

取决于日期格式和&amp;在date文本列中的时间,您可能需要使用内置的SQLite Date And Time Functions才能以相同的格式进行比较。