当前位置:网站首页>Basic use and upgrade of Android native database
Basic use and upgrade of Android native database
2022-07-04 23:03:00 【Just_ Paranoid】
android Native databases use
SQLiteOpenHelper: Database creation 、 Updated operation object
SQLiteDatabase: The operation object of data addition, deletion, modification and query
SQLiteStatement:SQL The operation object executed
sqlite Internal implementation
Insert :SQLiteStatement.executeInsert
to update 、 Delete :SQLiteStatement.executeUpdateDelete
Inquire about :SQLiteCursorDriver.query
performance optimization
1、 precompile SQL sentence , Repeated operation use SQLiteStatement
2、 With a transaction , Improve performance when doing data update operations
3、 Shut down in time Cursor
4、 Time consuming asynchronization
Basic use
// Create database : Inherit the of the system SQLiteOpenHelper, stay onCreate and onUpgrade Realize the creation and update of database
public class MyDbHelper extends SQLiteOpenHelper {
private static final String TAG = "MyDbHelper";
private static final String DB_NAME = "my.db";
private static final int DB_VERSION = 1;
public MyDbHelper(@Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create database
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Update the database
}
}
//2. Database management : Use singleton to manage the operation of database , Used to get a readable and writable SQLiteDatabase
public class MyDbManage {
private static MyDbManage myDbManage;
private final MyDbHelper myDbHelper;
private MyDbManage(Context context) {
myDbHelper = new MyDbHelper(context);
}
public static MyDbManage getInstance(Context context) {
if (myDbManage == null) {
synchronized (MyDbManage.class) {
if (myDbManage == null) {
myDbManage = new MyDbManage(context);
}
}
}
return myDbManage;
}
/** * Get a writable database * * @return SQLiteDatabase */
public SQLiteDatabase getWritableDatabase() {
return myDbHelper.getWritableDatabase();
}
}
//3. Database operation : For each entity , It is recommended to create a separate DAO, Easier maintenance
public class MyDaoSample {
public static final String TABLE_NAME = "user";// Table name
public static final String USER_NAME = "username";
public static final String AGE = "age";
public static final String SEX = "sex";
private static MyDaoSample myDaoSample;
private final SQLiteDatabase mDb;
private MyDaoSample() {
MyDbManage dbManage = MyDbManage.getInstance(CoreApplication.mApp);
mDb = dbManage.getWritableDatabase();
}
public static MyDaoSample getInstance() {
if (myDaoSample == null) {
synchronized (MyDaoSample.class) {
if (myDaoSample == null) {
myDaoSample = new MyDaoSample();
}
}
}
return myDaoSample;
}
public void insert() {
ContentValues values = new ContentValues();
values.put(USER_NAME, "susu");
values.put(AGE, 18);
mDb.beginTransaction();
mDb.insert(TABLE_NAME, null, values);
mDb.setTransactionSuccessful();
mDb.endTransaction();
}
}
Android Upgrade and update the native database OnUpgrade
Be careful :
1. Modify the database version number
2. rewrite OnUpgrade Method
//DBOpenHelper The database class
public class DBOpenHelper extends SQLiteOpenHelper
// Database version number
private static final int DB_VERSION = 2;
// initialization
private DBOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// Upgrade database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1) {
db.beginTransaction();
try {
// upgrade note table column
db.execSQL("ALTER TABLE " + NOTE_TABLE_NAME + " ADD COLUMN " + NOTE_IS_TOP_ID + " int;");
db.execSQL("ALTER TABLE " + NOTE_TABLE_NAME + " ADD COLUMN " + NOTE_TOP_DATE_ID + " long;");
db.execSQL("ALTER TABLE " + NOTE_TABLE_NAME + " ADD COLUMN " + NOTE_IS_CONTAIN_VOICE_ID + " int;");
db.execSQL("ALTER TABLE " + NOTE_TABLE_NAME + " ADD COLUMN " + NOTE_PIC_PATH_ID + " text;");
// upgrade folder table column
db.execSQL("ALTER TABLE " + FOLDER_TABLE_NAME + " ADD COLUMN " + FOLDER_IS_TODO + " int;");
//insert default values
String travel = mContext.getString(R.string.folder_travel);
String life = mContext.getString(R.string.folder_life);
String work = mContext.getString(R.string.folder_work);
db.execSQL("INSERT INTO "
+ FOLDER_TABLE_NAME
+ " VALUES ('1','"+travel+"', '0', '0','0');");
db.execSQL("INSERT INTO "
+ FOLDER_TABLE_NAME
+ " VALUES ('2','"+life+"', '0', '0','0');");
db.execSQL("INSERT INTO "
+ FOLDER_TABLE_NAME
+ " VALUES ('3','"+work+"', '0', '0','0');");
// create todo table
db.execSQL(" CREATE TABLE IF NOT EXISTS " + TODO_TABLE_NAME + " ( "
+ ID + " integer primary key autoincrement , "
+ TODO_CONTENT + " text , "
+ TODO_IS_IMPORTANT + " int , "
+ TODO_TIME + " long , "
+ TODO_REPEAT + " int , "
+ TODO_IS_COMPLETE + " int , "
+ TODO_IS_DELAY + " int , "
+ TODO_IS_DELETED + " int , "
+ TODO_PARENT_FOLDER_ID + " int , "
+ TODO_DATE + " long);");
db.setVersion(DB_VERSION);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
}
// If the database file does not exist , Only onCreate() Called ( This method is called once when the database is created )
public abstract void onCreate(SQLiteDatabase db);
// If the database file exists , Would call onUpgrade() Method to upgrade the database , And update the version number .
public abstract void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion);
OnCreate : If the database file does not exist ,SQLiteOpenHelper Creating a database file , Open the database , call onCreate() Method , In this method, you usually need to create a table 、 View and other components . The database is usually empty before creation , Therefore, there is no need to delete the relevant components in the database first .
OnUpgrade : When the system is constructing SQLiteOpenHelper Class , If the version number is different , Will automatically call onUpgrade function , Let you upgrade the database here .
Both the new version number and the old version number will be used as onUpgrade The arguments to the function come in , It is convenient for developers to know which version of the database should be upgraded from . When the upgrade is complete , The database will automatically store the latest version number as the current database version number .
Need to be right SQLite Upgrade the structure of the database :
SQLite Provides ALTER TABLE command , Allow users to rename or add new fields to existing tables , But you can't delete fields from the table .
And you can only add fields at the end of the table , such as , by Student Add two fields :
1 ALTER TABLE Student ADD COLUMN UserPhone VARCHAR;
2 ALTER TABLE Student ADD COLUMN UserNickName VARCHAR;
If you encounter complex modification operations , For example, while modifying , Data transfer is required , Then you can execute the following statement in a transaction to meet the requirement of modifying the table .
Change the table name to a temporary table
ALTER TABLE Student RENAME TO __temp__Student;Create new table
CREATE TABLE Student (UserId VARCHAR(32) PRIMARY KEY ,UserName VARCHAR(32) NOT NULL ,UserAddress VARCHAR(16) NOT NULL);Import data
INSERT INTO Student SELECT UserId, “”, UserAddress FROM __temp__Student;
perhaps
INSERT INTO Student() SELECT UserId, “”, UserAddress FROM __temp__Student;
- Be careful Double quotes ”” It is used to supplement the data that did not exist before
- Delete temporary table
DROP TABLE __temp__Student;
Through the above four steps , You can complete the migration from the old database structure to the new database structure , And it can also ensure that the data will not be lost for upgrading .
Of course , If the field is reduced , It can also be achieved by creating temporary tables .
Relevant reference
https://blog.csdn.net/linglingchenchen/article/details/123632277
边栏推荐
- Redis入门完整教程:哈希说明
- 实战模拟│JWT 登录认证
- 剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
- [machine learning] handwritten digit recognition
- 剑指Offer 68 - II. 二叉树的最近公共祖先
- 字体设计符号组合多功能微信小程序源码
- Attack and defense world misc advanced grace-50
- [roommate learned to use Bi report data processing in the time of King glory in one game]
- One of the commonly used technical indicators, reading boll Bollinger line indicators
- [graph theory] topological sorting
猜你喜欢
Qt加法计算器(简单案例)
Redis introduction complete tutorial: Collection details
Redis入门完整教程:Redis Shell
Attack and defense world misc advanced area ditf
攻防世界 MISC 进阶区 3-11
Redis入门完整教程:列表讲解
Network namespace
S32 Design Studio for ARM 2.2 快速入门
Redis入门完整教程:客户端通信协议
A complete tutorial for getting started with redis: redis shell
随机推荐
MySQL Architecture - logical architecture
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
C语言快速解决反转链表
On-off and on-off of quality system construction
S32 Design Studio for ARM 2.2 快速入门
SHP data making 3dfiles white film
Sobel filter
Async await used in map
[graph theory] topological sorting
The overview and definition of clusters can be seen at a glance
heatmap. JS picture hotspot heat map plug-in
Redis getting started complete tutorial: publish and subscribe
Redis入门完整教程:Bitmaps
ffmpeg快速剪辑
qt绘制网络拓补图(连接数据库,递归函数,无限绘制,可拖动节点)
【剑指offer】1-5题
Wechat official account solves the cache problem of entering from the customized menu
Redis入门完整教程:GEO
The small program vant tab component solves the problem of too much text and incomplete display
A complete tutorial for getting started with redis: hyperloglog