在Android中連接數(shù)據(jù)庫實現(xiàn)增刪改查操作通常使用SQLite數(shù)據(jù)庫。以下是實現(xiàn)增刪改查操作的一般步驟:
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"));
// 處理查詢結(jié)果
} 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();
以上是簡單的數(shù)據(jù)庫操作示例,實際應用中可能會根據(jù)具體需求進行更復雜的操作。在進行數(shù)據(jù)庫操作時需要注意線程安全性和異常處理,以確保數(shù)據(jù)操作的穩(wěn)定性和安全性。