在sqlite查询中引用字符串

时间:2013-11-02 10:26:43

标签: java android sqlite android-sqlite

我有一个用这个声明制作的数据库:

DATABASE_CREATE = "create table "
        + TABLE_BANDS + "(" + COLUMN_ID
        + " integer primary key autoincrement, " + COLUMN_NAME
        + " text unique not null, " + COLUMN_GENDER + " text, " + COLUMN_POPULARITY + " real not null);";

我在这句话中添加了一行:

private long addBand(String bandName, String gender) {
    ContentValues values = new ContentValues();
    values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\"" + bandName.trim().toLowerCase() + "\"");
    values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
    values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
    long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
            values);

    return insertId;
}

我得到了insertId> 0,所以我认为插入没问题。

然后我尝试用这段代码选择我刚插入的一行:

public Band getBand(String name) {
    Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
            new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \"" + name.trim().toLowerCase() + "\"", null,
            null, null, null);

    cursor.moveToFirst();
    Band band = getBandFromCursor(cursor);
    cursor.close();
    return band;
}

但它总是返回一个长度为0的游标。 我试图删除名称周围的引号,但在它查询后才能正常工作。

此外我尝试使用rawQuery,但结果是一样的。

Cursor cursor = database.rawQuery("Select * from " + BandsSQLiteOpenHelper.TABLE_BANDS + " where band_name = \"" + name.trim().toLowerCase() + "\"", null);

更新:

我试过单引号:

Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
            new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \'" + name.trim().toLowerCase() + "\'", null,
            null, null, null);

private long addBand(String bandName, String gender) {
    ContentValues values = new ContentValues();
    values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\'" + bandName.trim().toLowerCase() + "\'");
    values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
    values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
    long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
            values);

    return insertId;
}

如前插入正常,选择返回0行。

1 个答案:

答案 0 :(得分:1)

插入值时,我怀疑您需要在插入的值周围加上双引号,因为您在数据库创建字符串中指定字段为TEXT

至于你的rawQuery,试试这个: "SELECT * FROM " + BandsSQLiteOpenhelper.TABLE_BANDS + " WHERE band_name = '" + name.trim().toLowerCase() + "'";

在WHERE语句中使用字符串作为标识符时,请尝试使用单引号而不是双引号。