为什么sqlite表列_id不起作用

时间:2013-09-18 15:30:28

标签: android sqlite

我遇到了一个问题:在使用SQLite数据库& SimpleCursorAdapter,我明确地创建了一个包含_id主键列的表:

public class NoteDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notes_db";

private static final String NOTE_TABLE_NAME = "note";
private static final String NOTE_COL_ID = "_id";
private static final String NOTE_COL_TITLE = "title";
private static final String NOTE_COL_CONTENT = "content";
private static final String NOTE_COL_CREATED = "created";
private static final String NOTE_COL_MODIFIED = "modified";

private static final String[] NOTE_COL_PROJECTION = new String[] {
        NOTE_COL_TITLE, NOTE_COL_CONTENT, };

public NoteDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Create table
@Override
public void onCreate(SQLiteDatabase db) {
    String createNoteTableSql = "CREATE TABLE " + NOTE_TABLE_NAME + " ("
            + NOTE_COL_ID + " INTEGER PRIMARY KEY," + NOTE_COL_TITLE
            + " TEXT," + NOTE_COL_CONTENT + " TEXT," + NOTE_COL_CREATED
            + " INTEGER," + NOTE_COL_MODIFIED + " INTEGER" + ");";
    db.execSQL(createNoteTableSql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + NOTE_TABLE_NAME);

    // Create tables again
    onCreate(db);
}

由于SimpleCursorAdapter需要一个'Cursor'对象,所以我创建了函数:

    public Cursor getAllNotesCursor() {
    String selectQuery = "SELECT _id as _id, title, content FROM " + NOTE_TABLE_NAME;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    return cursor;
}

请注意,我需要使用SELECT _id as _id来使事情有效,SELECT _id, title...不起作用,你知道为什么吗?

0 个答案:

没有答案