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應用程序中方便地存儲和檢索數據。