简体   繁体   English

SQLiteOpenHelper如何返回SQLiteDatabase?

[英]How can SQLiteOpenHelper return SQLiteDatabase?

I know that SQLiteDatabase doesn't have any public constructor and I cannot create its object directly. 我知道SQLiteDatabase没有任何公共构造函数,因此无法直接创建其对象。

But then how is SQLiteOpenHelper able to return SQLiteDatabase reference using getReadableDatabase() or getWritableDatabase() ? 但是, SQLiteOpenHelper如何使用getReadableDatabase()getWritableDatabase()返回SQLiteDatabase引用?

Just because the constructor isn't public/visible doesn't mean it doesn't exist! 仅仅因为构造函数不是public / visible并不意味着它不存在!

SQLiteOpenHelper uses SQLiteDatabase 's static constructor openDatabase to create a new database instance. SQLiteOpenHelper使用SQLiteDatabase的静态构造函数openDatabase创建一个新的数据库实例。 It is public and has not been hidden so, although it is probably not a good idea, you could call it, directly, yourself. 它是公开的,并且没有被隐藏,因此,尽管这可能不是一个好主意,但您可以自己直接调用它。

According to the doc you would use it like this: 根据文档,您可以这样使用它:

   SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null); 

The first argument is a String giving the full path name for the new db. 第一个参数是一个字符串,它提供新数据库的完整路径名。 The second is the cursor factory. 第二个是游标工厂。 Passing null for the second arg will get you the default factory. 为第二个arg传递null将为您提供默认工厂。

Using the SQLiteOpenHelper guarantees that the db is correctly created and correctly initialized. 使用SQLiteOpenHelper确保正确创建和正确初始化数据库。 It also properly caches db instances, so that they aren't recreated every time you need them. 它还会适当地缓存数据库实例,这样就不会在您每次需要它们时都重新创建它们。 It is probably better to use it. 最好使用它。

Try this: 尝试这个:

Class Cdb.java: Cdb.java类:

public class Cdb extends SQLiteOpenHelper {

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

    Cdb(Context context) {
        super(context.getApplicationContext(), DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        // Upgrade here
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);

}

and then you may access the database as follows: 然后您可以按以下方式访问数据库:

Cdb openHelper = new Cdb(this);
SQLiteDatabase db = openHelper.getReadableDatabase();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM