Using SQLite database in Android
The following steps are required to use SQLite database in Android:
- To create a database in an Android application, you can use the SQLiteOpenHelper class to create and manage the database. First, create a class that extends SQLiteOpenHelper and override the following methods:
- In the onCreate() method, we create database tables.
- Upgrade database tables in this method, onUpgrade().
- Open the database: Before using the database in the application, it is necessary to open the database first. You can open the database using the getWritableDatabase() method or the getReadableDatabase() method.
- Performing database operations: You can use the methods of the SQLiteDatabase class to perform database operations such as adding, deleting, modifying, and querying data. Some commonly used methods are as follows:
- Execute SQL statement using execSQL().
- insert(): to add data.
- delete(): remove data.
- update(): Data is being updated.
- query(): retrieve data.
- Close database: After the application finishes using the database, it should be closed to release resources. The close() method can be used to close the database.
Here is a simple example:
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, name TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String dropTableQuery = "DROP TABLE IF EXISTS mytable";
db.execSQL(dropTableQuery);
onCreate(db);
}
}
// 使用数据库
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "John");
db.insert("mytable", null, values);
// 查询数据
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.d("Database", "id: " + id + ", name: " + name);
}
// 关闭数据库
db.close();
This is just a simple example, in actual use, more database operations may be needed. Additionally, attention should be paid to the design of data tables and data handling.