android sqlite 基本用法

要在应用程序中包含数据库,通常从 SQLiteOpenHelper 派生一个类 :

public class HelloDBHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final int DATABASE_NAME = "hello";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE ...");
        ...
    }
}

该帮助程序类负责打开(以及创建/更新,如果需要)数据库。使用它来获取 SQLiteDatabase 对象来访问数据:

SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query(...);
while (c.moveToNext()) {
    String name = c.getString(0);
    ...
}
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("column", value);
...
db.insertOrThrow("table", null, cv);