/*************************************************************************/
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) {
}
}
添加數據
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); // 插入第二條數據
更新數據
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("province_name", "湖北");
db.update("Province", values, "province_code = ?", new String[] {"09"});
刪除數據
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Province", "province_code = ?", new String[] {"09"});
查詢數據
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();
數據庫中的事務
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction(); // 開啓事務
try {
..............................................................
..............................................................
..............................................................
db.setTransactionSuccessful(); // 事務已經執行成功
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction(); // 結束事務
}
注:爲了確保endTransaction()方法一定會執行,將該方法放在finally方法裏面