我是一名新的 android 开发人员,正在开发一个具有登录屏幕的应用程序。
当应用程序启动时,它会检查数据库 (LoginDB) 是否存在。如果它不存在,那么我想创建数据库,创建表并插入 1 行。如果数据库存在,那么它将继续执行应用程序。
您如何确定特定数据库是否存在以及所需的表是否已经存在。
我使用的是安卓 2.2
我是一名新的 android 开发人员,正在开发一个具有登录屏幕的应用程序。
当应用程序启动时,它会检查数据库 (LoginDB) 是否存在。如果它不存在,那么我想创建数据库,创建表并插入 1 行。如果数据库存在,那么它将继续执行应用程序。
您如何确定特定数据库是否存在以及所需的表是否已经存在。
我使用的是安卓 2.2
SQLiteOpenHelper类有两个方法 onCreate 和 onUpdate 正是你需要的。如果没有数据库,那么它将调用 onCreate 方法,如果存在,它将调用 onUpdate 方法。查看Vogellas 网站以获取一个很好的示例
查找表是否存在于特定的数据库中。
SQLiteDatabase db = openOrCreateDatabase("your db file name",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor cursor = db.query("sqlite_master", new String[] { "name" },
"name=" + "'your table name'", null, null, null, null);
if (cursor.getCount() <= 0) {
//Table is not exists
}
else
{
//table is exists
}
Using this query you can check whether table is exist in DB or not,
SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';
otherwise,
in onCreate of database helper you have to use create query like as follow,
CREATE TABLE IF NOT EXISTS "+tablename+" ( "+ colums+");");