我只需要选择操作。因此,应在应用程序启动之前插入数据。这样做的最佳方式是什么?
答案 0 :(得分:1)
使用SQLiteOpenHelper的子类访问您的数据库。创建数据库时,onCreate
将被调用一次。
要使用您的数据库,您可以执行以下操作:
DBHelper db = new DBHelper(context);
db.getReadableDatabase().query(....);
db.close();
扩展SQLiteOpenHelper
做类似的事情(没有测试表创建的sql!):
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database.db";
private static final Integer DATABASE_VERSION = 1;
DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/*
* Called ONCE on the very first db access (when the db file is created)
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE mytable (_id PRIMARY KEY AUTOINCREMENT, value TEXT); \n" +
"INSERT INTO mytable (value) VALUES ('data'));");
}
/*
* Called every time you open a database
*/
@Override
public void onOpen(SQLiteDatabase db) {
}
/*
* Called ONCE if DATABASE_VERSION has changed since the last instantiation of DBHelper
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}