在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();