在Android中,可以使用SQLite數據庫進行數據存儲和檢索。以下是使用Android數據庫的一般步驟:
SQLiteOpenHelper
子類中創建數據庫。在onCreate()
方法中,可以定義表和字段。public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase";
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper(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);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升級數據庫時執行的操作
}
}
getWritableDatabase()
或getReadableDatabase()
方法打開數據庫。MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
insert()
方法向表中插入數據。ContentValues values = new ContentValues();
values.put("id", 1);
values.put("name", "John");
long newRowId = db.insert("myTable", null, values);
query()
方法從表中檢索數據。String[] projection = {"id", "name"};
String selection = "name = ?";
String[] selectionArgs = {"John"};
Cursor cursor = db.query("myTable", projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
// 處理數據
} while (cursor.moveToNext());
}
cursor.close();
update()
方法更新表中的數據。ContentValues values = new ContentValues();
values.put("name", "Jane");
String whereClause = "id = ?";
String[] whereArgs = {"1"};
int rowsUpdated = db.update("myTable", values, whereClause, whereArgs);
delete()
方法從表中刪除數據。String whereClause = "id = ?";
String[] whereArgs = {"1"};
int rowsDeleted = db.delete("myTable", whereClause, whereArgs);
close()
方法關閉數據庫。db.close();
以上是使用Android數據庫的基本步驟,可以根據具體需求進行調整和擴展。