coolweather项目总结
一、创建数据库和表
a.建表语句
<span style="font-size:18px;">create table City (id integer primary key autoincrement,</span>
<span style="font-size:18px;">city_name text, </span>
<span style="font-size:18px;">city_code text, </span>
<span style="font-size:18px;">province_id integer)</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">注意点:在实体类中将tablename 和 column_?? 变成常量 好处:防止在使用它们的时候出现文字错误,但是要注意在建表语句中注意空格。</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">b.在db包下创建CoolWeatherOpenHelper类。extends SQLiteOpenHelper</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">c.为每张对应的表建立实体类。记住将对应的构造方法写完整 有参数无参数最好都写上。</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">d.创建CoolWeatherDB类,这个类将一些常用的数据库操作封装起来</span>
<span style="font-size:18px;"><span style="font-size:18px;">注意点:使用单例模式,保证整个应用只有一个dbhelper对象</span>
<span style="font-size:18px;"> 具体操作: private static CoolWeatherDB coolWeaterDB;//静态</span>
<span style="font-size:18px;">/**</span>
<span style="font-size:18px;">* 将构造函数私有化,禁止这个类意外创建dbhelper实体</span></span>
<span style="font-size:18px;">**/</span>
<span style="font-size:18px;">private CoolWeatherDB (Context context){</span>
<span style="font-size:18px;"> CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context, DB_NAME, null, </span>
<span style="font-size:18px;">VERSION);</span>
<span style="font-size:18px;"> db = dbHelper.getWritableDatabase();</span>
<span style="font-size:18px;">}</span>
<span style="font-size:18px;">/**</span>
<span style="font-size:18px;">*对外提供获取CoolWeatherDB实体的方法</span>
<span style="font-size:18px;">**/</span>
<span style="font-size:18px;">public synchronized static CoolWeatherDB getInstance(Context context){</span>
<span style="font-size:18px;">if(coolWeatherDB == null){</span>
<span style="font-size:18px;">coolWeatherDB = new CoolWeatherDB(context)</span>
<span style="font-size:18px;">}</span>
<span style="font-size:18px;">return coolWeatherDB;</span>
<span style="font-size:18px;">}</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">数据库的读写操作:</span>
<span style="font-size:18px;">/**</span>
<span style="font-size:18px;">*保存一个实例</span>
<span style="font-size:18px;">**/</span>
<span style="font-size:18px;">public void saveProvince(Province province){</span>
<span style="font-size:18px;"> if(province != null){</span>
<span style="font-size:18px;">ContetnValues values = new ContentValues();</span>
<span style="font-size:18px;">values.put("字段名",province.getName);</span>
<span style="font-size:18px;">....</span>
<span style="font-size:18px;">db.insert("表名",null,values);</span>
<span style="font-size:18px;"> }</span>
<span style="font-size:18px;">}</span>