Android数据库面向对象之增、删、改、查

关于数据库等封装之前有写过一篇博客Android数据库面向对象之增、删、改、查这篇博客写的是将数据库存储在sd卡中,android6.0以后关于sd卡的操作就需要动态申请权限,如果在工具类中使用时权限的申请就没有那么方便,即使在activity或者fragment中时候,使用的频次比较高时,老是申请权限也比较麻烦,存储在data目录下虽然存储的数据大小有限,但是不需要去做权限的申请,使用起来方便很多,这里是针对data目录下的存储的封装,基本上和sd卡的存储封装大同小异,有些细微的变化。

系统提供了SQLiteOpenHelper这个类用于数据的创建和数据库的版本管理,在使用是extends SQLiteOpenHelper该类,会要求去重写onCreate()方法和onUpgrade()方法,在数据创建时会回调onCreate()方法,数据库版本更新是会回调onUpgrade()方法;

public class MySqliteHelper extends SQLiteOpenHelper {
    private BaseDao baseDao;

    public MySqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public MySqliteHelper(Context context) {
        super(context, ConstantValue.DATABASE_NAME, null, ConstantValue.DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //执行建表语句
        db.execSQL(baseDao.createTable());
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //数据库版本变动会回调这里
    }

    public synchronized <T extends BaseDao<M>, M> T
    getDataHelper(Class<T> clazz, Class<M> entityClass) {
        try {
            //利用反射实例化BaseDao
            baseDao = clazz.newInstance();
            //初始化BaseDao中的参数
            baseDao.init(entityClass);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) baseDao;
    }
}

MySqliteHelper弄好后,需要定义一个接口提供数据库增删改查操作的一系列方法;

public interface IBaseDao<T> {
    /**
     * 插入数据库
     * @param entity  插入的数据对象
     * @return
     */
    Long insert(T entity);
    /**
     * 批量插入数据库
     * @param entity 插入的数据对象
     * @return
     */
    void insert(List<T> entity);

    /**
     * 更新数据库
     * @return
     */
    int update(ContentValues contentValues, String whereClause, String[] whereArgs);

    /**
     * 删除数据库
     * @return
     */
    int delete(String selection,String[] selectionArgs);

    /**
     * 查询数据
     * @param where  查询条件
     * @return
     */
    List<T> query(T where);

    /**
     * 查询数据
     * @param where  查询条件
     * @param orderBy  查询排序
     * @param startIndex  开始的位置
     * @param limit  查询限制条件
     * @return
     */
    List<T> query(T where, String selection, String[] selectionArgs, String orderBy, Integer startIndex, Integer limit);

    /**
     * 查询数据 用于多条件查询
     * @param sql  查询语句
     * @return
     */
    List<T> query(String sql);
}

数据增删改查接口定义好了,需要一个实现类去做具体的增删改查的逻辑;

public abstract class BaseDao<T> implements IBaseDao<T> {
    private static volatile MySqliteHelper helper;
    private boolean isInit = false;
    private Class<T> entityClass;
    private SQLiteDatabase database;
    private String tableName;
    /**
     * 维护这表名与成员变量名的映射关系
     * key---》表名
     * value --》Field
     */
    private HashMap<String, Field> cacheMap;

    public static MySqliteHelper getInstance(Context context) {
        if (helper == null) {
            synchronized (MySqliteHelper.class) {
                if (helper == null) {
                    helper = new MySqliteHelper(context.getApplicationContext());
                }
            }
        }
        return helper;
    }

    protected synchronized boolean init(Class<T> entity) {
        if (!isInit) {
            entityClass = entity;
            //getReadableDatabase  getWritableDatabase 创建或者打开数据库
            //如果数据库不存在则会创建数据库,如果数据库存在直接打开数据库
            //默认情况下都是打开或者创建可读可写的数据库,如果磁盘已盘就是可读数据库
            database = helper.getWritableDatabase();
            //判断数据库是否打开
            if (!database.isOpen()) {
                return false;
            }
            tableName = getTableName();
            cacheMap = new HashMap<>();
            //缓存维护映射关系
            initCacheMap();
            isInit = true;
        }
        return isInit;
    }

    /**
     * 维护映射关系
     */
    private void initCacheMap() {
        String sql = "select * from " + this.tableName + " limit 1 , 0";
        Cursor cursor = null;
        try {
            cursor = database.rawQuery(sql, null);
            //表的列名数组
            String[] columnNames = cursor.getColumnNames();
            //拿到Filed数组
            Field[] colmunFields = entityClass.getFields();
            for (Field filed : colmunFields) {
                //设置私有可以访问
                filed.setAccessible(true);
            }
            //开始找对应关系
            for (String columnName : columnNames) {
                //如果找到对应的Field就赋值给他
                Field columnFiled = null;
                for (Field filed : colmunFields) {
                    String filedName = "";
                    if (filed.getAnnotation(DbFiled.class) != null) {
                        filedName = filed.getAnnotation(DbFiled.class).value();
                    } else {
                        filedName = filed.getName();
                    }
                    //如果表的列名等于了成员变量的注解名字
                    if (columnName.equals(filedName)) {
                        columnFiled = filed;
                        break;
                    }
                }
                //找到了对应关系
                if (columnFiled != null) {
                    cacheMap.put(columnName, columnFiled);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭游标
            cursor.close();
        }
        Log.e("cacheMap--->", cacheMap.size() + "");
    }

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

    @Override
    public void insert(List<T> entity) {
        //批量插入采用事务
        database.beginTransaction();
        for (T data : entity) {
            insert(data);
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }

    @Override
    public int update(ContentValues contentValues, String whereClause, String[] whereArgs) {
        int result = -1;
        result = database.update(tableName, contentValues, whereClause, whereArgs);
        return result;
    }

    @Override
    public int delete(String selection, String[] selectionArgs) {
        int result = database.delete(tableName, selection, selectionArgs);
        return result;
    }

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

    @Override
    public List<T> query(T where, String selection, String[] selectionArgs, String orderBy, Integer startIndex, Integer limit) {
        String limitString = "";
        if (startIndex != null && limit != null) {
            limitString = startIndex + " , " + limit;
        }
        Cursor cursor = database.query(tableName, null, selection, selectionArgs,
                null, null, orderBy, limitString);
        List<T> result = getResult(cursor, where);
        //关闭游标
        cursor.close();
        return result;
    }

    @Override
    public List<T> query(String sql) {
        return null;
    }

    /**
     * 根据查询条件获取查询结果
     *
     * @param cursor 数据库游标
     * @param where  查询条件
     * @return 根据查询条件返回的结果
     */
    private List<T> getResult(Cursor cursor, T where) {
        List list = new ArrayList();
        Object item;
        while (cursor.moveToNext()) {
            try {
                item = where.getClass().newInstance();
                //遍历缓存的映射关系
                Iterator<Map.Entry<String, Field>> iterator = cacheMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Field> entry = iterator.next();
                    //得到列名
                    String colomunName = entry.getKey();
                    //然后以列名拿到 列名在游标的位置
                    Integer columnIndex = cursor.getColumnIndex(colomunName);
                    Field field = entry.getValue();
                    Class<?> type = field.getType();
                    if (columnIndex != -1) {
                        //反射赋值
                        if (type == String.class) {
                            field.set(item, cursor.getString(columnIndex));
                        } else if (type == Integer.class || type == int.class) {
                            field.set(item, cursor.getInt(columnIndex));
                        } else if (type == Double.class || type == double.class) {
                            field.set(item, cursor.getDouble(columnIndex));
                        } else if (type == Long.class || type == long.class) {
                            field.set(item, cursor.getLong(columnIndex));
                        } else if (type == byte[].class) {
                            field.set(item, cursor.getBlob(columnIndex));
                        } else {
                            continue;
                        }
                    }
                }
                list.add(item);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 将缓存的map数据转成ContentValues
     *
     * @param map
     * @return
     */
    private ContentValues getContentValues(Map<String, String> map) {
        ContentValues contentValues = new ContentValues();
        Set<String> keys = map.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = map.get(key);
            if (value != null) {
                contentValues.put(key, value);
            }
        }
        return contentValues;
    }

    /**
     * 根据数据对象和数据库表字段,将数据转成key value的形式
     *
     * @param entity 数据对象
     * @return 转换后获取到的数据
     */
    private Map<String, String> getValues(T entity) {
        Map<String, String> result = new HashMap<>();
        //遍历缓存数据,并进行映射
        Iterator<Field> fieldIterator = cacheMap.values().iterator();
        while (fieldIterator.hasNext()) {
            Field colmunToFiled = fieldIterator.next();
            String cacheKey = "";
            String cacheValue = "";
            if (colmunToFiled.getAnnotation(DbFiled.class) != null) {
                cacheKey = colmunToFiled.getAnnotation(DbFiled.class).value();
            } else {
                cacheKey = colmunToFiled.getName();
            }
            try {
                if (null == colmunToFiled.get(entity)) {
                    continue;
                }
                cacheValue = colmunToFiled.get(entity).toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.put(cacheKey, cacheValue);
        }
        return result;
    }

    /**
     * 创建表语句
     *
     * @return
     */
    public abstract String createTable();

    /**
     * 表名
     *
     * @return
     */
    public abstract String getTableName();
}

在实现类中提供了createTable()和getTableName()两个抽象方法,具体的创建表语句和表名需要根据实际的由子类去实现;

public class PersonDao extends BaseDao<Person> {
    @Override
    public String createTable() {
        String sql = "create table if not exists " + getTableName() + "(" + ConstantValue._ID + " Integer primary key," + ConstantValue.NAME + " varchar(10)," + ConstantValue.AGE + " Integer)";
        return sql;
    }

    @Override
    public String getTableName() {
        return ConstantValue.TABLE_NAME;
    }
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DbFiled {
    String value();
}
public class ConstantValue {
    //数据库库版本
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "name.db";
    //表名
    public static final String TABLE_NAME = "person";
    //数据库存储字段
    public static final String _ID = "_id";
    public static final String NAME = "name";
    public static final String AGE = "age";
}

接下来调用下增删改查方法,看下实现的如何,在使用之前需要先初始化MySqliteHelper和创建BaseDao对象;

private PersonDao dataHelper = BaseDao.getInstance(this).getDataHelper(PersonDao.class, Person.class);

初始化完毕后就可以调用相应的方法,进行数据库操作了,先看下单条数据的插入;

/**
     * 插入数据库
     *
     * @param view
     */
    public void addDB(View view) {
        Person person = new Person();
        person._id = 100;
        person.name = "张国焘";
        person.age = 89;
        dataHelper.insert(person);
    }

利用Sqlite数据库工具打开,单条数据插入成功;
在这里插入图片描述

/**
     * 批量插入数据库
     *
     * @param view
     */
    public void addMoreDB(View view) {
        List<Person> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Person person = new Person();
            person._id = i;
            person.name = "张国焘" + i;
            person.age = i;
            list.add(person);
        }
        dataHelper.insert(list);
    }

批量数据也插入到数据中了;
在这里插入图片描述

/**
     * 修改数据
     *
     * @param view
     */
    public void updateDB(View view) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(ConstantValue.NAME, "李四8");
        String where = ConstantValue.NAME + "=?";
        String[] whereArgs = new String[]{"张国焘7"};
        dataHelper.update(contentValues, where, whereArgs);
    }

在这里插入图片描述
第八条数据修改成功;

/**
     * 删除数据
     *
     * @param view
     */
    public void deleteDB(View view) {
        String where = ConstantValue.NAME + "=?";
        String[] selectionArgs = new String[]{"张国焘5"};
        dataHelper.delete(where, selectionArgs);
    }

在这里插入图片描述
第六条数据被删除了;

/**
     * 查询数据库
     *
     * @param view
     */
    public void queryDB(View view) {
        Person user = new Person();
        user.name = "张国焘1";
        List<Person> query = dataHelper.query(user);
        Log.e("TAG", "数据库查询数据" + query.size());
        for (Person user1 : query) {
            Log.e("TAG", "姓名:" + user1.name + "年龄:" + user1.age);
        }
    }

在这里插入图片描述
在这里插入图片描述

/**
     * 分页查询
     * @param view
     */
    public void queryByLimit(View view){
        Person user = new Person();
        user.name = "张国焘1";
        List<Person> query = dataHelper.query(user,null,null,null,0,8);
        Log.e("TAG", "数据库查询数据" + query.size());
        for (Person user1 : query) {
            Log.e("TAG", "姓名:" + user1.name + "年龄:" + user1.age);
        }
    }

源码地址

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值