在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) {
// 如果數據庫版本更新,可以在此處執行相應的操作
}
}
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();
// 更新數據
ContentValues updateValues = new ContentValues();
updateValues.put("name", "Jane");
db.update("mytable", updateValues, "id=?", new String[]{"1"});
// 刪除數據
db.delete("mytable", "id=?", new String[]{"1"});
db.close();
以上就是在Android中使用SQLite數據庫的基本步驟,可以根據具體需求來擴展和優化代碼。