以下是一个简单的使用SQLiteOpenHelper来创建、升级、增删改查数据库的例子:
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) {
// 创建表
String CREATE_TABLE = "CREATE TABLE " + "mytable" + "("
+ "ID" + " INTEGER PRIMARY KEY AUTOINCREMENT," + "NAME" + " TEXT,"
+ "AGE" + " INTEGER" + ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 更新数据库
db.execSQL("DROP TABLE IF EXISTS " + "mytable");
onCreate(db);
}
// 增加记录
public boolean insertData(String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", name);
cv.put("AGE", age);
long result = db.insert("mytable", null, cv);
return result != -1;
}
// 删除记录
public boolean deleteData(int id) {
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete("mytable", "ID = ?", new String[] { Integer.toString(id) });
return result > 0;
}
// 更新记录
public boolean updateData(int id, String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", name);
cv.put("AGE", age);
int result = db.update("mytable", cv, "ID = ?", new String[] { Integer.toString(id) });
return result > 0;
}
// 查询记录
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query("mytable", new String[] { "ID", "NAME", "AGE" }, "ID = ?", new String[] { Integer.toString(id) }, null, null, null);
return cursor;
}
}
使用方法:
DatabaseHelper dbHelper = new DatabaseHelper(context);
// 插入数据
dbHelper.insertData("John", 25);
// 删除数据
dbHelper.deleteData(1);
// 更新数据
dbHelper.updateData(1, "Jane", 30);
// 查询数据
Cursor cursor = dbHelper.getData(1);
if (cursor.moveToFirst()) {
do {
String name =