【问题标题】:How to get data from database separated by comma?如何从用逗号分隔的数据库中获取数据?
【发布时间】:2014-03-23 20:41:56
【问题描述】:

我创建了两个表:

出勤数据

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

类数据

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

我想从class_data 表中获取class_id,其中date 列的值在currtime 中,即2014 年3 月24 日凌晨1:41:12

但是查询时会出现如下错误:

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;
}

【问题讨论】:

  • 您应该在日期字段中使用 DateTime 类型,而不是 text 类型

标签: java android sql database sqlite


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 1970-01-01
    • 2017-09-27
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    相关资源
    最近更新 更多