当前位置:网站首页>[database] SQLite version upgrade and downgrade
[database] SQLite version upgrade and downgrade
2022-06-12 11:39:00 【ScriptGirl】
Reference resources :https://www.jianshu.com/p/65923fa3e3dc
1 Normal all use process
1.1 Define global variables
public static SQLiteHelper dbHelper;
public static String folder = "android.xxx.xxx"; // Database storage address
public static String file = "database.db"; // Database name
public static int DB_VERSION = 1; // Version number of the database
public static SQLiteDatabase db; // database
1.2 Initialize database ( stay MainActivity Medium or Services in )
The resulting database is stored in a public folder , Even if you uninstall APP, The database will not be lost .
static void init_db(Context context) {
String pathname = GetDir.getDir(Constant.folder);
File file = new File(pathname, Constant.file);
try {
if(!file.exists()){
file.createNewFile();
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
context.sendBroadcast(intent);
}
} catch (IOException e) {
Log.v("main", "failed1");
e.printStackTrace();
}
try {
Constant.dbHelper = new SQLiteHelper(context, pathname+"/"+Constant.file, null, Constant.DB_VERSION);
Constant.db = Constant.dbHelper.getWritableDatabase(); // call SQLiteHelper.OnCreate()
Log.v("main", "new db");
} catch (IllegalArgumentException e) {
Log.v("main", "failed2");
e.printStackTrace();
Constant.dbHelper.onUpgrade(Constant.db, Constant.DB_VERSION - 1, Constant.DB_VERSION);
}
}
among GetDir.getDir as follows :
public class GetDir {
public static String getDir(String pathname) {
String sdcardPath = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdcardPath + File.separator + pathname /*+ File.separator + "Files"*/);
if (dir.exists()) {
return dir.toString();
} else {
dir.mkdirs();
return dir.toString();
}
}
}
1.3 stay SQLiteHelper Define the steps of database initialization in , Database upgrade and downgrade
public class SQLiteHelper extends SQLiteOpenHelper {
static final String TAG = "SQLiteHelper";
public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
/** * Create new table */
@Override
public void onCreate(SQLiteDatabase db) {
Log.v(TAG,"onCreate");
db.execSQL("CREATE TABLE IF NOT EXISTS mytable (name varchar(15), age varchar(5))");
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.v(TAG,"onDowngrade");
if(oldVersion == 3 && newVersion == 2){
// from 3 drop to 2
Log.i(TAG, "onDowngrade: from 3 drop to 2");
db.execSQL("create table tmp_mytable as select name, age from mytable"); // Create a new table from the old table , It is equivalent to deleting score Column
db.execSQL("drop table mytable");
db.execSQL("alter table tmp_mytable rename to mytable");
}
}
/** * When the detection is different from the database version created last time , Delete the table before creating a new table */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.v(TAG,"onUpgrade");
switch (newVersion){
case 2: {
// Add... To the table score Field , Initial value 0
Log.i(TAG, "onUpgrade: newVersion = 2");
// The way 1
db.execSQL("alter table mytable add score varchar(5)");
ContentValues values = new ContentValues();
values.put("score", "0");
db.update("mytable ", values, "name!=?", new String[]{
""});
// The way 2
// First create a temporary table that meets the requirements
db.execSQL("CREATE TABLE IF NOT EXISTS mytable (name varchar(15), age varchar(5), score varchar(5))");
// Copy data from old table to temporary table
ContentValues values = new ContentValues();
values.put("score", "0");
db.execSQL("INSERT INTO tmp_mytable (name, age) SELECT name, age from mytable");
db.update("tmp_mytable", values, "name!=?", new String[]{
""}); // as long as name Not empty , All modified score by 0
// Delete old table
db.execSQL("DROP TABLE IF EXISTS mytable");
// Rename the temporary table to the old table name
db.execSQL("ALTER TABLE tmp_mytable RENAME TO mytable");
break;
}
case 3: {
// Delete... From both tables region Field
Log.i(TAG, "onUpgrade: newVersion = 3");
db.execSQL("create table tmp_mytable as select name, age from mytable"); // If you write where 1 = 2 Only the table structure will be copied , Don't copy content
db.execSQL("drop table mytable");
db.execSQL("alter table tmp_mytable rename to mytable");
break;
}
default:
break;
}
}
}
2. sqlite Version update
2.1 Method 1 Hard upgrade Not recommended
The first is a hard upgrade method , Delete all old tables , Then recreate all the tables in the database . This method is not elegant , Deleting data is at risk of being unrecoverable , This approach is not recommended .
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Hard upgrade
db.execSQL("DROP TABLE IF EXISTS numbers");
db.execSQL("DROP TABLE IF EXISTS recordInfo");
onCreate(db);
2.2 Recommended approach 2 The species are as follows
/** * When the detection is different from the database version created last time , Delete the table before creating a new table */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.v(TAG,"onUpgrade");
switch (newVersion){
case 2: {
// Add... To the table score Field , Initial value 0
Log.i(TAG, "onUpgrade: newVersion = 2");
// The way 1
// First, check whether there is score Field , without , To upgrade it
ContentValues values = new ContentValues();
values.put("score", "0");
if(!checkColumnExist(db, "mytable", "score")){
db.execSQL("alter table mytable add score varchar(5)");
db.update("mytable", values, "name!=?", new String[]{
""});
}
// The way 2
// First create a temporary table that meets the requirements
db.execSQL("CREATE TABLE IF NOT EXISTS mytable (name varchar(15), age varchar(5), score varchar(5))");
// Copy data from old table to temporary table
ContentValues values = new ContentValues();
values.put("score", "0");
db.execSQL("INSERT INTO tmp_mytable (name, age) SELECT name, age from mytable");
db.update("tmp_mytable", values, "name!=?", new String[]{
""}); // as long as name Not empty , All modified score by 0
// Delete old table
db.execSQL("DROP TABLE IF EXISTS mytable");
// Rename the temporary table to the old table name
db.execSQL("ALTER TABLE tmp_mytable RENAME TO mytable");
break;
}
case 3: {
// Delete... From both tables region Field
Log.i(TAG, "onUpgrade: newVersion = 3");
db.execSQL("create table tmp_mytable as select name, age from mytable"); // If you write where 1 = 2 Only the table structure will be copied , Don't copy content
db.execSQL("drop table mytable");
db.execSQL("alter table tmp_mytable rename to mytable");
break;
}
default:
break;
}
}
}
Check whether a table column exists
/** * Check whether a table column exists * @param db * @param tableName Table name * @param columnName Name * @return */
private boolean checkColumnExist(SQLiteDatabase db, String tableName, String columnName) {
boolean result = false ;
Cursor cursor = null ;
try{
// Look up a line
cursor = db.rawQuery( "SELECT * FROM " + tableName + " LIMIT 0", null );
result = cursor != null && cursor.getColumnIndex(columnName) != -1 ;
}catch (Exception e){
Log.e(TAG,"checkColumnExists1..." + e.getMessage()) ;
}finally{
if(null != cursor && !cursor.isClosed()){
cursor.close() ;
}
}
return result ;
}
2. Downgrade
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion == 3 && newVersion == 2){
// from 3 drop to 2
Log.i(TAG, "onDowngrade: from 3 drop to 2");
db.execSQL("create table tmp_mytable as select name, age from mytable");
db.execSQL("drop table mytable");
db.execSQL("alter table tmp_tb1 rename to mytable");
}
}
边栏推荐
- Design of secure chat tool based on C #
- Simple solution of regular expression
- AcWing 1995. Meet and greet (simulation)
- arm交叉编译链下载地址
- Golang Foundation (7)
- Heavyweight proxy cache server squid
- systemctl里万恶的203
- UML series articles (30) architecture modeling -- product diagram
- 字节序(网络/主机)转换
- 21 reasons why you need social media QR code
猜你喜欢

Les humains veulent de l'argent, du pouvoir, de la beauté, de l'immortalité, du bonheur... Mais les tortues ne veulent être qu'une tortue.

【藍橋杯單片機 國賽 第十一届】

Unity 连接 Microsoft SQLSERVER 数据库

Clj3-100alh30 residual current relay

Record the pits encountered when using JPA

【clickhouse专栏】基础数据类型说明

ReentrantLock源码分析

QT based travel query and simulation system

6.6 分離卷積

Humans want to have money, power, beauty, eternal life and happiness... But turtles only want to be a turtle
随机推荐
【clickhouse专栏】基础数据类型说明
Unity 连接 Microsoft SQLSERVER 数据库
Construction and construction of meta Universe System
ARM指令集之杂类指令
字节序 - 如何判断大端小端
套接字实现 TCP 通信流程
字节序(网络/主机)转换
AcWing 1912. Odometer (enumeration)
进程的创建和回收
[the 11th national competition of Blue Bridge Cup single chip microcomputer]
MATLAB中stairs函数使用
多普勒效应的基本原理
K58. Chapter 1 installing kubernetes V1.23 based on kubeadm -- cluster deployment
Doris records service interface calls
[Blue Bridge Cup SCM 11th National race]
Naming specification / annotation specification / logical specification
MySQL锁查漏补缺
arm交叉编译链下载地址
Byte order (network / host) conversion
ARM指令集之伪指令