SQLiteOpenHelper是Android提供的一个管理数据库的工具类,可用于管理数据库的创建和版本更新。SQLiteOpenHelper是一个抽象类,所以我们想要使用它,就必须创建它的子类,并且拓展它的onCreate(SQLiteDatabase db)和onUpdate(SQLiteDatabase db,int oldVersion,int newVersion)方法。

SQLiteOpenHelper包含如下常用方法:

构造函数

/**     * Create a helper object to create, open, and/or manage a database.     * This method always returns very quickly.  The database is not actually     * created or opened until one of {@link #getWritableDatabase} or     * {@link #getReadableDatabase} is called.     *     * @param context to use to open or create the database     * @param name of the database file, or null for an in-memory database     * @param factory to use for creating cursor objects, or null for the default     * @param version number of the database (starting at 1); if the database is older,     *     {@link #onUpgrade} will be used to upgrade the database; if the database is     *     newer, {@link #onDowngrade} will be used to downgrade the database     */    public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {        this(context, name, factory, version, null);    }    /**     * Create a helper object to create, open, and/or manage a database.     * The database is not actually created or opened until one of     * {@link #getWritableDatabase} or {@link #getReadableDatabase} is called.     *     * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be     * used to handle corruption when sqlite reports database corruption.</p>     *     * @param context to use to open or create the database     * @param name of the database file, or null for an in-memory database     * @param factory to use for creating cursor objects, or null for the default     * @param version number of the database (starting at 1); if the database is older,     *     {@link #onUpgrade} will be used to upgrade the database; if the database is     *     newer, {@link #onDowngrade} will be used to downgrade the database     * @param errorHandler the {@link DatabaseErrorHandler} to be used when sqlite reports database     * corruption, or null to use the default error handler.     */    public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version,            DatabaseErrorHandler errorHandler) {        if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version);        mContext = context;        mName = name;        mFactory = factory;        mNewVersion = version;        mErrorHandler = errorHandler;    }

onCreate(SQLiteDatabase db)

<span style="font-family:SimSun;">/**     * Called when the database is created for the first time. This is where the     * creation of tables and the initial population of the tables should happen.     *     * @param db The database.     */    public abstract void onCreate(SQLiteDatabase db);</span>
onUpdate(SQLiteDatabase db,int oldVersion,int newVersion)
<span style="font-size:18px;">  /**     * Called when the database needs to be upgraded. The implementation     * should use this method to drop tables, add tables, or do anything else it     * needs to upgrade to the new schema version.     *...</span><pre name="code" class="java"><span style="font-size:18px;">     *</span>...     * @param db The database.     * @param oldVersion The old database version.     * @param newVersion The new database version.     */    public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

  getWritableDatabase()  
 <span style="font-size:18px;"> /**     * Create and/or open a database that will be used for reading and writing.     * The first time this is called, the database will be opened and     * {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be     * called.     *......     * @throws SQLiteException if the database cannot be opened for writing     * @return a read/write database object valid until {@link #close} is called     */    public SQLiteDatabase getWritableDatabase() {        synchronized (this) {            return getDatabaseLocked(true);        }    }</span>
getReadableDatabase()
<span style="font-size:18px;">/**     * Create and/or open a database.  This will be the same object returned by     * {@link #getWritableDatabase} unless some problem, such as a full disk,     * requires the database to be opened read-only.  In that case, a read-only     * database object will be returned.  If the problem is fixed, a future call     * to {@link #getWritableDatabase} may succeed, in which case the read-only     * database object will be closed and the read/write object will be returned     * in the future.     *     *     *     * @throws SQLiteException if the database cannot be opened     * @return a database object valid until {@link #getWritableDatabase}     *     or {@link #close} is called.     */    public SQLiteDatabase getReadableDatabase() {        synchronized (this) {            return getDatabaseLocked(false);        }    }</span>

onClose()

<span style="font-family:SimSun;font-size:18px;">  /**     * Close any open database object.     */    public synchronized void close() {        if (mIsInitializing) throw new IllegalStateException("Closed during initialization");        if (mDatabase != null && mDatabase.isOpen()) {            mDatabase.close();            mDatabase = null;        }    }</span>
onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)
<span style="font-family:SimSun;font-size:18px;">   /**     * Called when the database needs to be downgraded. This is strictly similar to     * {@link #onUpgrade} method, but is called whenever current version is newer than requested one.     * However, this method is not abstract, so it is not mandatory for a customer to     * implement it. If not overridden, default implementation will reject downgrade and     * throws SQLiteException     *     * <p>     * This method executes within a transaction.  If an exception is thrown, all changes     * will automatically be rolled back.     * </p>     *     * @param db The database.     * @param oldVersion The old database version.     * @param newVersion The new database version.     */    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {        throw new SQLiteException("Can't downgrade database from version " +                oldVersion + " to " + newVersion);    }</span>


其中,这个类有两个构造函数,我们这只要看SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version,
DatabaseErrorHandler errorHandler)就行了,

context用于打开或新建数据库的上下文,

name 数据库文件的名称,如果为空,那么使用的就是内存中的数据库了,

factory 用于新建cursor对象的,为空的话就是用默认的,

version 数据库的版本号(从1开始),如果当前的数据库是旧的,那么会调用onUpgrade来更新数据库,反之,会调用onDowngrade方法来回退数据库

errorHandler 当sqlite记录数据库损毁会使用它,一般设为null用默认的。


onCreate(SQLiteDatabase db):只在数据库第一次创建时才会被调用,通常在这个方法里面会做一些建表和数据初始化的操作。


onUpdate(SQLiteDatabase db,int oldVersion,int newVersion):当数据库需要升级的时候会调用这个方法,在这个方法中,应该做一些数据库表结构的更新操作。oldVersion代表数据库之前的版本号,newVersion代表当前数据库的版本号。那么在哪里指定数据库的版本号呢?当我们创建SQLiteOpenHelper对象时,必须指定一个version参数,该参数就决定了所使用的数据库的版本——也就是说,数据库的版本是由我们自己来控制的,只要某次创建SQLiteOpenHelper对象时指定的版本号高于之前的版本号,就会触发这个方法。特别指出,这个方法是在一个事物中执行的,也就是说这方法执行的过程中一旦发生了异常,那么所有的改变都会自动的回滚。

onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) 当数据库需要降级的时候会调用。严格的来说,这个方法和onUpdate方法是一样的。不过它和onUpdate的区别在于:

1、onDowngrade 用于版本回退,也就是当newVersion小于oldVersion的时候会调用,

2、onDowngrade不是抽象方法,没有强制我们去实现它,默认的它会抛出SQLiteException异常。

3、onDowngrade要求的api版本最低是10,10之前是没有的。


getWritableDatabase()新建或者打开一个用于读写的数据库,第一次被调用的时候,数据库会被打开,并且onCreate,onUpgrade或onOpen(注:如果数据库已经被打开,就会调用这个方法,如果还没有被打开,调用的是onUpgrade或者onDowngrade)会被调用。

getReadableDatabase()新建或者打开一个数据库。如果没有问题的话,调用该方法得到的数据库和通过调用getWritableDatabase()方法来得到的数据库是一样的。但如果磁盘满了,得到的只是一个只读的数据库,倘若使用getWritableDatabase()打开数据库就会报错。

onClose() 关闭所有的数据库对象。但我们完成了数据库操作之后,必须去关闭数据库连接,否则会发生内存泄漏。

总的来说SQLiteOpenHelper类就这么些东西,挺简单的。

Android之Sqlite开发(1)—简介


更多相关文章

  1. Flutter的一生
  2. Android解析WindowManagerService(三)Window的删除过程
  3. Android(安卓)Camera OMXCameraAdapter.cpp初始化分析
  4. 2018最新大厂Android面试真题
  5. 单元测试--Android单元测试学习总结(junit+Mockito+PowerMockito)
  6. android开发之Android(安卓)ActionBar完全解析
  7. Android(安卓)Volley完全解析(三),定制自己的Request
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. Android初级-Android 日志输出和Debug跟
  2. [Android]【安卓】Content Provider详解
  3. Android桌面悬浮窗
  4. Android(安卓)Binder入门指南之Binder Na
  5. ImageButton设置 android:background添加
  6. 逐帧(Frame)动画
  7. ADB命令大全
  8. Android(安卓)SDK 离线下载安装更新至4.0
  9. Android(安卓)Studio调试设置的断点无效
  10. Android属性(android:gravity)的说明