Android内置SQLite是一种轻量级的数据库管理系统,用于在Android应用程序中存储和检索数据。它提供了一个简单的方法来创建和管理数据库,并执行各种SQL操作。
以下是使用Android内置SQLite的详细介绍:
dependencies {
implementation 'androidx.sqlite:sqlite:2.1.0'
}
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建表格和初始化数据
String createTableQuery = "CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT)";
db.execSQL(createTableQuery);
String insertDataQuery = "INSERT INTO mytable (id, name) VALUES (1, 'John'), (2, 'Jane')";
db.execSQL(insertDataQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 更新数据库结构
String dropTableQuery = "DROP TABLE IF EXISTS mytable";
db.execSQL(dropTableQuery);
onCreate(db);
}
}
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase(); // 或者 dbHelper.getReadableDatabase();
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "Tom");
long newRowId = db.insert("mytable", null, values);
// 查询数据
String[] projection = {"id", "name"};
String selection = "name = ?";
String[] selectionArgs = {"John"};
Cursor cursor = db.query("mytable", projection, selection, selectionArgs, null, null, null);
// 更新数据
ContentValues updatedValues = new ContentValues();
updatedValues.put("name", "Jack");
String whereClause = "id = ?";
String[] whereArgs = {"1"};
int rowsUpdated = db.update("mytable", updatedValues, whereClause, whereArgs);
// 删除数据
String deleteQuery = "id = ?";
String[] deleteArgs = {"2"};
int rowsDeleted = db.delete("mytable", deleteQuery, deleteArgs);
db.close();
以上是使用Android内置SQLite的详细介绍。通过创建和管理数据库,并执行各种SQL操作,您可以在Android应用程序中方便地存储和检索数据。