在Android中使用SQLite數(shù)據(jù)庫需要進(jì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) {
// 如果數(shù)據(jù)庫版本更新,可以在此處執(zhí)行相應(yīng)的操作
}
}
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
long id = 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"));
// do something with the data
} while (cursor.moveToNext());
}
cursor.close();
// 更新數(shù)據(jù)
ContentValues updateValues = new ContentValues();
updateValues.put("name", "Jane");
db.update("mytable", updateValues, "id=?", new String[]{"1"});
// 刪除數(shù)據(jù)
db.delete("mytable", "id=?", new String[]{"1"});
db.close();
以上就是在Android中使用SQLite數(shù)據(jù)庫的基本步驟,可以根據(jù)具體需求來擴(kuò)展和優(yōu)化代碼。