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");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章