从SQLiteDatabase中选择值。代码1错误?

时间:2014-03-07 12:06:20

标签: android

我正在创建一个应用来存储条目。我试图从数据库中选择相关信息并显示。单击任务后,信息将显示在屏幕上,并显示包含该信息的任务。

这是我的输入屏幕类,其中显示了值。

    getDAO = new DAO(this);
    Cursor showDiaryEntries = getDAO.queryDiary(Diary.DiaryItem.FULL_PROJECTION, Diary.DiaryItem.COLUMN_NAME_DIARY_TITLE+" = "+fieldTitle, null);

    Long fieldDate = showDiaryEntries.getLong(1);
    Long fieldTime = showDiaryEntries.getLong(2);
    String fieldEntry = showDiaryEntries.getString(3);

    mDate.setText(String.valueOf(fieldDate));
    Log.i(TAG,"Field Date "+ fieldDate);
    mTime.setText(String.valueOf(fieldTime));
    Log.i(TAG,"Field Time "+ fieldTime);
    mEntry.setText(fieldEntry);
    Log.i(TAG,"Field Entry "+ fieldEntry);

logcat的:

03-07 07:00:22.186: E/AndroidRuntime(1411): FATAL EXCEPTION: main 03-07 07:00:22.186: E/AndroidRuntime(1411):
 java.lang.RuntimeException: Unable to start activity
 ComponentInfo{com.democo.mydiary/com.democo.mydiary.DiaryEntryActivity}:
 android.database.sqlite.SQLiteException: near "there": syntax error
 (code 1): , while compiling: SELECT diaryTitle, diaryDate, diaryTime,
 diaryEntry, diaryLat, diaryLong FROM diary WHERE (diaryTitle = Hi
 there) ORDER BY diaryDate DESC

由于

3 个答案:

答案 0 :(得分:3)

更改

Cursor showDiaryEntries = getDAO.queryDiary(Diary.DiaryItem.FULL_PROJECTION, Diary.DiaryItem.COLUMN_NAME_DIARY_TITLE+" = "+fieldTitle, null);

Cursor showDiaryEntries = getDAO.queryDiary(Diary.DiaryItem.FULL_PROJECTION, Diary.DiaryItem.COLUMN_NAME_DIARY_TITLE+" = '"+fieldTitle+"'", null);

您错过了' '

WHERE(diaryTitle = 你好

修改

无论如何,如果日记的标题包含像'的字符,你的代码是非常危险的,你可以使用语法x =?并将您的代码编辑为以下内容:

cursor = db.query(true,
        "table_name",
        "what should return",
        "diaryName=?", /* here.. it's the WHERE arg anyway */
        new String[] { fieldTitle },    /** what should be added */
        null, null, null, null);

您使用不同的方式进行查询,因此我使用了普通查询。

您也可以使用预准备语句。使用compileStatement并使用SQLiteStatement

示例:

SQLiteStatement stmt = db.compileStatement("SELECT diaryTitle, diaryDate, diaryTime,\n" +
        " diaryEntry, diaryLat, diaryLong FROM diary WHERE (diaryTitle " +
        "= ?) ORDER BY diaryDate DESC");
stmt.bindString(1, fieldTitle);
stmt.execute();

无论如何,对于准备好的陈述,你没有Cursor

答案 1 :(得分:2)

在您的选择查询中:

"...WHERE (diaryTitle = Hi there) ORDER BY..." 

在引号

中添加diaryTitle(因为它是一个字符串)的值

答案 2 :(得分:1)

文字字段必须是单引号: 即:

"... WHERE (diaryTitle = '"  + searchField +"') ORDER BY ..." 

INSERT,UPDATE或DELETE时相同。