在Android中連接數據庫實現增刪改查操作通常使用SQLite數據庫。以下是實現增刪改查操作的一般步驟:
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 mytable (id INTEGER PRIMARY KEY, name TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
long result = db.insert("mytable", null, values);
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
// 處理查詢結果
} while (cursor.moveToNext());
}
cursor.close();
ContentValues values = new ContentValues();
values.put("name", "Mike");
int rowsAffected = db.update("mytable", values, "id=?", new String[] { "1" });
int rowsAffected = db.delete("mytable", "id=?", new String[] { "1" });
db.close();
以上是簡單的數據庫操作示例,實際應用中可能會根據具體需求進行更復雜的操作。在進行數據庫操作時需要注意線程安全性和異常處理,以確保數據操作的穩定性和安全性。