-1

我有一个用这个语句制作的数据库:

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 行。

4

1 回答 1

1

插入值时,我怀疑您是否需要在插入的值周围加上双引号,因为您在 DB Creation 字符串中指定了字段为TEXT.

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

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

于 2013-11-02T10:33:01.797 回答