Android使用ORM思想封装数据库

什么是ORM?
ORM,即Object-Relational Mapping(对象关系映射),它的作用是在关系型数据库和业务实体对象之间作一个映射,这样,我们在具体的操作业务对象的时候,就不需要再去和复杂的SQL语句打交道,只需简单的操作对象的属性和方法。

举例
在Java Web中,hibernate就是实现了这样的功能。通过引入ORM,不但可以减少程序员的代码量,更重要的是方便不同数据库之间的迁移,极大的减少了耦合。

在Android开发中,有一些开源的库,也是实现了如此的功能,比如Litepal

这篇文章将简要的实现一些ORM的思想,代码包含了常用的对数据库的操作,但并不解耦,仅供参考。
整个表管理的是城市、天气以及更新时间,测试过以后。均运行良好。

public class WeatherSqlHelper extends SQLiteOpenHelper {

    private volatile static WeatherSqlHelper sInstance;

    private static final int version = 1;

    private static final String db_name = "weather.db";

    public static WeatherSqlHelper getIntance(Context cxt){
        if(sInstance == null){
            synchronized (WeatherSqlHelper.class) {
                if(sInstance == null){
                    sInstance = new WeatherSqlHelper(cxt, db_name, null, version);
                }
            }
        }
        return sInstance;
    }

    public WeatherSqlHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub
        arg0.execSQL("create table status(id integer primary key autoincrement," +
                "city varchar(10)," +
                "weather varchar(10)," +
                "updateTime varchar(50))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub
    }

    //查看数据库中是否存在指定城市名的信息
    public static boolean contain(Context cxt, String str){

        Cursor cursor = getIntance(cxt).getReadableDatabase().rawQuery("select * from status where city=?", new String[]{str});
        if (cursor.getCount() != 0) {
            return true;
        }
        return false;
    }

    //获得全部数据
    public static Cursor getAllData(Context cxt){
        return getIntance(cxt).getReadableDatabase().rawQuery("select * from status", null);
    }

    //更新某个城市状态,如果不存在该条信息,则插入一条
    public static void updateCityData(Context cxt, String cityStr, String weatherStr, String timeStr){
        if(contain(cxt, cityStr)){
            getIntance(cxt).getReadableDatabase().execSQL("update status set weather=?,updateTime=? where city=?", new String[] { weatherStr, timeStr, cityStr});
        }else{
            getIntance(cxt).getReadableDatabase().execSQL("insert into status values(null, ?, ?, ?)", new String[] { cityStr, weatherStr, timeStr });
        }
    }

    //删除某条城市的行
    public static void deleteRow(Context cxt, String str){
        getIntance(cxt).getReadableDatabase().execSQL("DELETE FROM status WHERE city=?", new String[]{str});

    }

    //清空数据库数据
    public static void clearDb(Context cxt){
        getIntance(cxt).getReadableDatabase().execSQL("delete from status");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章