Android手寫數(shù)據(jù)庫框架設(shè)計(jì)(刪改查)

1、我們接著上一篇文章講,實(shí)現(xiàn)數(shù)據(jù)庫框架的刪改查的功能,建議先看上篇文章后再看這篇文章,文章地址:Android手寫數(shù)據(jù)庫框架設(shè)計(jì)(增)。
我們插入數(shù)據(jù)庫的操作在BaseDao里面完成的,具體的插入代碼:

 @Override
    public Long insert(T entity) {
        Map<String, String> map = getValues(entity);
        ContentValues contentValues = getContentValues(map);
        Long result = mDatabase.insert(tableName, null, contentValues);
        return result;
    }

2、在IBaseDao接口中,我們?cè)黾觿h改查的方法。

public interface IBaseDao<T> {
    //插入數(shù)據(jù)
    Long insert(T t);

    //更新數(shù)據(jù)
    int update(T entity,T where);1

    //刪除數(shù)據(jù)
    int delete(T where);2

    //查詢數(shù)據(jù)
    List<T> query(T where);3

    List<T> query(T where,String orderBy,Integer startIndex,Integer limit);4

    List<T> query(String sql);5
}

更新數(shù)據(jù)的方法1處代碼傳入兩個(gè)參數(shù),entity是要跟改的實(shí)體類,where是,2,3,4,5處的代碼就不做過多的解讀了。

BaseDao中刪改查的方法:

 @Override
    public int update(T entity, T where) {
        int result = -1;
        Map values = getValues(entity);
        /**
         * 將條件對(duì)象轉(zhuǎn)化為map
         */
        Map whereClause = getValues(where);
        Condition condition = new Condition(whereClause);
        ContentValues contentValues = getContentValues(values);
        result = mDatabase.update(tableName, contentValues,condition.getWhereClause(), condition.getWhereArgs());
        return result;
    }

 @Override
    public int delete(T where) {
        Map map = getValues(where);
        Condition condition = new Condition(map);
        /**
         * id=1 數(shù)據(jù)
         * id=?      new String[]{String.value(1)}
         */
        int result = mDatabase.delete(tableName,condition.getWhereClause(),condition.getWhereArgs());
        return result;
    }

  @Override
    public List<T> query(T where) {
        return query(where, null, null, null);
    }

    @Override
    public List<T> query(T where, String orderBy, Integer startIndex, Integer limit) {
        Map map = getValues(where);
        String limitString = null;
        if (startIndex != null && limit != null) {
            limitString = startIndex + " , " + limit;
        }
        Condition condition = new Condition(map);
        /**
         *    public Cursor query(String table, String[] columns, String selection,
         String[] selectionArgs, String groupBy, String having,
         String orderBy, String limit)
         */
        Cursor cursor = mDatabase.query(tableName, null, condition.getWhereClause(), condition.getWhereArgs(), null, null, orderBy, limitString);
        List<T> result = getResult(cursor, where);
        return result;
    }

在這里我們重點(diǎn)關(guān)注Condition類和getRelsult(cursor, where)方法,Condition類里面的代碼:

/**
     * 封裝修改語句
     */
    class Condition {
        /**
         * 查詢條件 "name=?&&password=?"
         */
        private String whereClause;

        private String[] whereArgs;

        /**
         * sqliteDatabase.update(tableName, contentValues, whereClause, whereArgs);
         * sqliteDatabase.delete(tableName, whereClause, whereArgs);
         */
        public Condition(Map<String, String> whereClause) {
            ArrayList list = new ArrayList();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(" 1=1 ");
            Set keys = whereClause.keySet();
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                String value = whereClause.get(key);
                if (value != null) {
                   /*
                    拼接條件查詢語句
                    1=1 and name =? and password=?
                     */
                    stringBuilder.append(" and " + key + " =?");
                    list.add(value);
                }
            }
            this.whereClause = stringBuilder.toString();
            this.whereArgs = (String[]) list.toArray(new String[list.size()]);
        }

        public String getWhereClause() {
            return whereClause;
        }

        public String[] getWhereArgs() {
            return whereArgs;
        }
    }

Condition的作用主要是Map轉(zhuǎn)換為修改數(shù)據(jù)庫和查詢數(shù)據(jù)庫的條件字符串和給條件語句等號(hào)后的變量賦值的String數(shù)組。

getRelsult(cursor, where)的代碼:

 private List<T> getResult(Cursor cursor, T where) {
        ArrayList list = new ArrayList();
        Object item;
        while (cursor.moveToNext()) {
            try {
                item = where.getClass().newInstance();
                /**
                 * 列名  name
                 * 成員變量名  Filed;
                 */
                Iterator iterator = cacheMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    //得到列名
                    String columName = (String) entry.getKey();
                    //然后以列名拿到列名在游標(biāo)的位置
                    int columnIndex = cursor.getColumnIndex(columName);
                    //拿到cacheMap里面key對(duì)應(yīng)的field
                    Field field = (Field) entry.getValue();
                    //拿到成員變量的類型
                    Class type = field.getType();
                    if (columnIndex != -1) {
                        if (type == String.class) {
                            //反射方式賦值
                            field.set(item, cursor.getString(columnIndex));
                        } else if (type == Double.class) {
                            field.set(item, cursor.getDouble(columnIndex));
                        } else if (type == Long.class) {
                            field.set(item, cursor.getLong(columnIndex));
                        } else if (type == Integer.class) {
                            field.set(item,cursor.getInt(columnIndex));
                        }else if (type == byte[].class){
                            field.set(item,cursor.getBlob(columnIndex));
                        }else {
                            //不支持的類型
                            continue;
                        }
                    }
                }
                list.add(item);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

這個(gè)方法主要是對(duì)查詢的游標(biāo)cursor操作,通過傳進(jìn)來的where實(shí)例化對(duì)象,賦值后添加到集合,返回。

調(diào)用端的代碼:

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    IBaseDao<User> userDao;
//    IBaseDao<DownFile> downDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userDao = BaseDaoFactory.getInstance().getDataHelper(UserDao.class, User.class);
//        downDao = BaseDaoFactory.getInstance().getDataHelper(DownDao.class, DownFile.class);

    }

    public void save(View view) {
        for (int i = 0; i < 4; i++) {
            User user = new User("lcty", "123456");
            userDao.insert(user);
        }
    }

    public void delete(View view) {
        User user = new User();
        user.setName("haha");
        userDao.delete(user);
    }

    public void queryList(View view) {
        User where = new User();
        where.setName("haha");
        List<User> list = userDao.query(where);
        Log.i(TAG, "查詢到  " + list.size() + "  條數(shù)據(jù)");
    }

    public void update(View view) {
        User where = new User();
        where.setName("lcty");
        User user = new User("haha", "123456789");
        userDao.update(user, where);
    }
}

效果我就不貼了,感興趣的伙伴可以自己敲一遍看下效果,分析完畢,歡迎交流。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容