Table of contents
2. Introduction to SQLite database
1. Create a class that inherits SQLiteOPenHelper
4. Update the table to add fields
I. Introduction
When we use Android for development, we inevitably use data, so we need to use a database to operate on the data. The Android system has built-in SQlite.
2. Introduction to SQLite database
1. What is a SQLite database?
SQLite is a lightweight relational database . It has fast computing speed, takes up few resources, and only takes up a few hundred KB of storage space in the memory.
2.Features
- lightweight
- independence
- Isolation
- Cross-platform
- safety
- Multilingual interface
3.SQLite operation API
Android SDK provides a series of classes and interfaces for operating databases. Commonly used database operation classes include:
SQLiteOpenHelper class (this is what we use today)
onCreate(SQliteDatabase db) | When the database is first created, it will be called |
onIpgrade(SQliteDatabase db, int i, int i1) | Automatically called when database is upgraded |
getWritableDatabase() | Open a read/write database |
getReadableDatabase() | Open a readable database |
close() | Close database |
• This class is an abstract class used for database creation and database version updates.
SQLiteDatabase class
• This class is a database access class that encapsulates a series of database operation APIs and can add, delete, modify, and query data.
Cursor interface
• is a cursor interface, used as the return value in database operations, equivalent to the result set ResultSet.
4.SQLite data types
- integer: integer type
- real: floating point type
- text: text type
- blob: binary type
3. Use of SQlite database
1. Create a class that inherits SQLiteOPenHelper
1. First create a project, and then create a class. What I created here is the MySQLiteOpenHelper class. You can create a db package and put the class in the directory.
2. Inherit SQLiteOPenHelper, and click to implement the onCreate method and onUpgrade method to create and upgrade the database.
Don't be afraid of the red light bulb. Just click on the red light bulb to construct its constructor.
2.Create database
We rewrite the construction method of MySQLiteOpenHelper and write down the next three parameters so that they can be called later, and then write the database name and database version.
//部分代码
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
Context mContext;
public MySQLiteOpenHelper(@Nullable Context context) {
super(context, "test", null, 1);
this.mContext = context;
}
}
3.Create database table
1. Determine the fields and types of the table. I will create a user table as an example.
Field | Field Type | describe |
---|---|---|
id | integer primary key auto-increment | |
zh | text | account |
mm | text | password |
xm | text | Name |
yes | integer | Phone number |
2. Defining an attribute is equivalent to creating a user table statement, which is actually similar to the mysql statement.
3. Call SQLiteDatabase.execSQL(CREATE_USER) in the onCreate method, which contains the attributes you just defined.
You can use Toast to prompt that when the program starts successfully, whether the database and database tables are created will only be executed once.
//部分代码
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public static String CREATE_USER = "create table user (" +
"id integer primary key autoincrement," +
"zh text," +
"mm text," +
"xm text," +
"sjh integer)";
Context mContext;
public MySQLiteOpenHelper(@Nullable Context context) {
super(context, "test", null, 1);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_USER);
Toast.makeText(mContext, "数据库首次创建成功!", Toast.LENGTH_SHORT).show();
}
}
4. Add a database to MainActivity, add a database instance, and then initialize the database.
MainActivity.java
//完整代码
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import com.example.myapplication.db.MySQLiteOpenHelper;
public class MainActivity extends AppCompatActivity {
private MySQLiteOpenHelper mySQLiteOpenHelper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData() {
mySQLiteOpenHelper = new MySQLiteOpenHelper(this);
db = mySQLiteOpenHelper.getWritableDatabase();
}
}
When the operation is successful and Toast is used, the page will prompt
5. Android provides the function of viewing the database. Click on App Inspection of the villain avatar at the bottom below, and you can see our database library and database tables.
For convenience, I created the database and data table together. If you run Create Database first, you need to add a database table to the database. I will talk about how to do it later.
4. Update the table to add fields
1. Add fields to the onUpgrade update table.
2. The database version is increased by +1.
//部分代码
public mySqliteOpenHelper(@Nullable Context context) {
//数据库的版本随着数据库每一次更新+1,原来版本1变成版本2
super(context, "user.db", null, 2);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//可以多次操作,更新数据库的方法
switch (i) {
case 2:
String sql = "ALTER TABLE user"
+ " ADD COLUMN avatar text";
sqLiteDatabase.execSQL(sql); // 执行修改表,添加字段的逻辑。
case 1:
// 当前版本就是2,所以目前代码不会进入 case 2: .. 里面来,只会进入 case 1 里面
// xxx 注意,这里不要 break; 要能一直升级。
}
}
3. Run the program again and check the database table. You can see that the avat field has been added.
Complete code
MySQLiteOpenHelper.java
package com.example.myapplication.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public static String CREATE_USER = "create table user (" +
"id integer primary key autoincrement," +
"zh text," +
"mm text," +
"xm text," +
"sjh integer)";
Context mContext;
public MySQLiteOpenHelper(@Nullable Context context) {
super(context, "test", null, 2);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_USER);
Toast.makeText(mContext, "数据库首次创建成功!", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//可以多次操作,更新数据库的方法
switch (i) {
case 1:
String sql = "ALTER TABLE user"
+ " ADD COLUMN avatar text";
sqLiteDatabase.execSQL(sql); // 执行修改表,添加字段的逻辑。
case 2:
// 当前版本就是2,所以目前代码不会进入 case 2: .. 里面来,只会进入 case 1 里面
// 注意,这里不要 break; 要能一直升级。
}
}
}
Expand
Adding a table is similar to updating table fields, except that you need to write a table creation statement, and the sqLiteDatabase.execSQL() method can be executed directly in onUpgrade (be sure to remember the database version +1 )
Summarize
SQLiteOpenHelper is an auxiliary class used in Android to manage SQLite databases. The SQLiteOpenHelper class is an important class for operating SQLite databases. Through the methods it provides, we can easily create and manage SQLite databases. It is simple and easy to use, the code is easy to understand, and it is suitable for novices.