Android-Sqlite-升级操作

一想到Android到数据库,只需要想到一个类 SQLiteOpenHelper,然后写一个类继承 SQLiteOpenHelper,重写构造方法,对数据库进行配置

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
  public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
      super(context, name, factory, version);
  }
}

SqliteDatabase数据库,所写的所有SQL语句都是通过系统sqlite.c文件执行成数据库文件的,SQlite数据库是关系型数据库,轻量级,体积小等特点

Android中的数据库升级,什么时候需要数据库升级?

答:例如:当发布上线的APP,已有用户在使用此APP,而这个APP的某张表只有name,age,现在还缺少一个字段,就需要数据库是增加表字段 同时保证其他数据不受影响。

在以前的数据库版本号上+1就能执行 onUpgrade 方法

private static final int VERSION = 2;

增加表字段,新增加的表字段 要允许为空

db.execSQL("alter table "+TABLE_NAME+" add sex text null");
package liudeli.datastorage.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    public static MySQLiteOpenHelper mySQLiteOpenHelper;

    /**
     * 由于表名每次使用很频繁,所有定义成常量
     */
    public static final String TABLE_NAME = "student_table";

    private static final String DB_NAME = "person_info.db";
    private static final int VERSION = 2;

    public synchronized static MySQLiteOpenHelper getInstance(Context context) {
        if (null == mySQLiteOpenHelper) {
            mySQLiteOpenHelper = new MySQLiteOpenHelper(context, DB_NAME, null, VERSION);
        }
        return mySQLiteOpenHelper;
    }

    /**
     * 当开发者调用 getReadableDatabase(); 或者 getWritableDatabase();
     * 就会通过此构造方法配置的信息 来创建 person_info.db 数据库
     * 此方法的另外作用是,如果存着数据库就打开数据库,不存着数据库就创建数据库
     * @param context 上下文
     * @param name    数据库名
     * @param factory 游标工厂
     * @param version 版本,最低为1
     */
    private MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    /**
     * 此方法是何时调用? ,是需要开发者调用 getReadableDatabase(); 或者 getWritableDatabase();
     * 此方法的作用是,如果没有表就创建打开,如果有表就打开
     * @param db 可执行SQL语句
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table "+TABLE_NAME+"(_id integer primary key autoincrement, name text, age integer);");
    }

    /**
     * 此方法用于数据库升级
     * @param db 可执行SQL语句
     * @param oldVersion 以前旧版本的版本号
     * @param newVersion 现在目前最新的版本号
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("alter table "+TABLE_NAME+" add sex text null");
    }
}

升级成功后的 sex 字段:

猜你喜欢

转载自www.cnblogs.com/android-deli/p/10085272.html