查询Android数据库是否存在!

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3386667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:59:12  来源:igfitidea点击:

Query if Android database exists!

androiddatabase

提问by Ally

I have created a database for my android app which contains static data and does not require update/delete functionality thus when the app starts, I want to check if the db exists and if not then execute my dbAdapter class. I know its a simple if statement but I was just wondering the most efficient way to query whether the db exists.

我为我的 android 应用程序创建了一个数据库,其中包含静态数据并且不需要更新/删除功能,因此当应用程序启动时,我想检查数据库是否存在,如果不存在,则执行我的 dbAdapter 类。我知道它是一个简单的 if 语句,但我只是想知道查询数据库是否存在的最有效方法。

Cheers

干杯

回答by rds

I'd rather check the existence of the file directly:

我宁愿直接检查文件的存在:

private static boolean doesDatabaseExist(Context context, String dbName) {
    File dbFile = context.getDatabasePath(dbName);
    return dbFile.exists();
}

回答by Mathias Conradt

/**
 * Check if the database exist and can be read.
 * 
 * @return true if it exists and can be read, false if it doesn't
 */
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        // database doesn't exist yet.
    }
    return checkDB != null;
}

where DB_FULL_PATH is the path to your database file.

其中 DB_FULL_PATH 是数据库文件的路径。

And the reason I am not just checking if a file exists is because it would not tell whether (a) it's an sqlite db file, (b) the file is not corrupt and can actually be read, i.e. due to partial download or however it has been created.

我不只是检查文件是否存在的原因是因为它无法判断 (a) 它是否是一个 sqlite db 文件,(b) 该文件没有损坏并且实际上可以读取,即由于部分下载或但是它已经被创造了。

回答by userdelroot

When you initialize the below class with:

当您使用以下类初始化以下类时:

mOpenHelper = new DatabaseHelper(getContext());

That will automatically create the database if it is not present. It also allows you upgrade the database by changing the DB_VER to a higher number.

如果数据库不存在,它将自动创建数据库。它还允许您通过将 DB_VER 更改为更高的数字来升级数据库。

Then so you are able to query the database use:

然后你就可以查询数据库使用:

 SQLiteDatabase db = mOpenHelper.getWritableDatabase();

the above gets you db.query()& db.insert()etc methods.

以上为您提供了db.query()db.insert()等方法。

private static class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "db_name.db";
    private static final int DB_VER = 1;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VER);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE table_name (" + "_id INTEGER PRIMARY KEY, "
                + " column_name_2 TEXT );");


                .execSQL("INSERT INTO table_name "
                        + "(column_name_2) "
                        + "VALUES " + "('hello world');");


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        Log.w(TAG + "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        try {
            db.execSQL("DROP TABLE IF EXISTS table_name");
            onCreate(db);

        } catch (SQLException e) {
            Log.e(TAG + "getting exception "
                    + e.getLocalizedMessage().toString());
        }
    }

}

回答by Imran Rana

it's simple: Open your database in try block with path of da databse like:

很简单:在 try 块中使用 da 数据库路径打开您的数据库,例如:

try{
   SQLiteDatabase   dbe = SQLiteDatabase.openDatabase("/data/data/bangla.rana.fahim/databases/dictionary", null,0);
            Log.d("opendb","EXIST");
            dbe.close();
            }

if an exception occurs then database doesn't exit so create it:

如果发生异常,则数据库不会退出,因此创建它:

catch(SQLiteException e){
                Log.d("opendb","NOT EXIST");

            SQLiteDatabase db = openOrCreateDatabase("dictionary", MODE_PRIVATE, null);
                    db.execSQL("CREATE TABLE IF NOT EXISTS LIST(wlist varchar);");

                    db.execSQL("INSERT INTO LIST VALUES('???');");
                    db.execSQL("INSERT INTO LIST VALUES('???');"); //whatever you want
                 db.close();
}

that's it you are done :)

就是这样你完成了:)

回答by Holger Behrens

I tried the version as provided by Mathias Conradt but I found that to simply check if DB != null is insufficient. I have amended to this:

我尝试了 Mathias Conradt 提供的版本,但我发现仅仅检查 DB != null 是不够的。我已修改为:

         /**
         * Check if the database exist and can be read.
         *
         * @return true if it exists and can be read, false if it doesn't
         */
        private boolean checkDataBase(String InDBFile) {
            SQLiteDatabase checkDB = null;
            boolean res = false;
            try {
                checkDB = SQLiteDatabase.openDatabase(InDBFile, null,
                        SQLiteDatabase.OPEN_READONLY);
                res = (checkDB.getVersion() > 0);
                checkDB.close();
            } catch (SQLiteException e) {
                // database doesn't exist yet.
                Log.e("checkDataBase", "Selected file could not be opened as DB.");

                res = false;
            }
            return res;
        }

回答by Lina Shyshova

I have found an even simpler solution:

我找到了一个更简单的解决方案:

context.databaseList().contains("table_name")

context.databaseList().contains("table_name")

回答by himanreddy

Create a global database helper class object in your main activity. In the MainActivity's onCreate() function try this:

在您的主要活动中创建一个全局数据库助手类对象。在 MainActivity 的 onCreate() 函数中试试这个:

//global database helper variable

DatabaseHelper dbh;

//in the onCreate()

if(dbh.getReadableDatabase()!=null)
//view the list

else
//create db