Android 为了让我们能够更加方便地管理数据库,专门提供了一个 SQLiteOpenHelper 帮助类,借助这个类就可以非常简单地对数据库进行创建和升级
新建一个类继承 SQLiteOpenHelper,给该类创建构造方法
[java] view plain copy
public class CoolWeatherOpenHelper extends SQLiteOpenHelper {
/*
* Province省份
*
* */
public static final String CREATE_PROVINCE = "create table Province(id integer primary key autoincrement,province_name text,province_code text)";
/*
* City城市
*
* */
public static final String CREATE_CITY = "create table City(id integer primary key autoincrement,city_name text,city_code text,province_code text)";
/*
* Country县
*
* */
public static final String CREATE_COUNTRY = "create table Country(id integer primary key autoincrement,country_name text,country_code text,city_code text)";
public CoolWeatherOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_PROVINCE);
db.execSQL(CREATE_CITY);
db.execSQL(CREATE_COUNTRY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
添加数据
[java] view plain copy
CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(this, "cool_weather", null, 1);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("province_name", "山东");
values.put("province_code", "07");
db.insert("Province", null, values); // 插入第一条数据
values.clear();
// 开始组装第二条数据
values.put("province_name", "山西");
values.put("province_code", "09");
db.insert("Province", null, values); // 插入第二条数据
更新数据
[java] view plain copy
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("province_name", "湖北");
db.update("Province", values, "province_code = ?", new String[] {"09"});
删除数据
[java] view plain copy
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Province", "province_code = ?", new String[] {"09"});
查询数据
[java] view plain copy
SQLiteDatabasedb = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Province", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String priovice_name = cursor.getString(cursor.getColumnIndex("province_name"));
String province_code = cursor.getString(cursor.getColumnIndex("provice_code"));
Log.d("MainActivity", "province name is " + priovice_name);
Log.d("MainActivity", "province code is " + province_code);
} while (cursor.moveToNext());
}
cursor.close();