在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数据库的基本步骤,可以根据具体需求来扩展和优化代码。