在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();
以上是简单的数据库操作示例,实际应用中可能会根据具体需求进行更复杂的操作。在进行数据库操作时需要注意线程安全性和异常处理,以确保数据操作的稳定性和安全性。