在Android中創建數據庫可以通過以下步驟來完成:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 創建表格的SQL語句
String createTableSql = "CREATE TABLE mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";
db.execSQL(createTableSql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 數據庫版本升級時調用,可執行相應的表結構變更操作
// 例如添加新的表、刪除舊的表等
}
}
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase(); // 或者dbHelper.getReadableDatabase();
// 插入數據
ContentValues values = new ContentValues();
values.put("name", "John");
long rowId = db.insert("mytable", null, values);
// 查詢數據
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
// 處理查詢結果
}
// 更新數據
ContentValues updateValues = new ContentValues();
updateValues.put("name", "Tom");
int rowsAffected = db.update("mytable", updateValues, "id=?", new String[]{"1"});
// 刪除數據
int rowsDeleted = db.delete("mytable", "id=?", new String[]{"1"});
db.close();