1、我们接着上一篇文章讲,实现数据库框架的删改查的功能,建议先看上篇文章后再看这篇文章,文章地址:Android手写数据库框架设计(增)。
我们插入数据库的操作在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接口中,我们增加删改查的方法。
public interface IBaseDao<T> {
//插入数据
Long insert(T t);
//更新数据
int update(T entity,T where);1
//删除数据
int delete(T where);2
//查询数据
List<T> query(T where);3
List<T> query(T where,String orderBy,Integer startIndex,Integer limit);4
List<T> query(String sql);5
}
更新数据的方法1处代码传入两个参数,entity是要跟改的实体类,where是,2,3,4,5处的代码就不做过多的解读了。
BaseDao中删改查的方法:
@Override
public int update(T entity, T where) {
int result = -1;
Map values = getValues(entity);
/**
* 将条件对象转化为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 数据
* 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;
}
在这里我们重点关注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转换为修改数据库和查询数据库的条件字符串和给条件语句等号后的变量赋值的String数组。
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();
//然后以列名拿到列名在游标的位置
int columnIndex = cursor.getColumnIndex(columName);
//拿到cacheMap里面key对应的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;
}
这个方法主要是对查询的游标cursor操作,通过传进来的where实例化对象,赋值后添加到集合,返回。
调用端的代码:
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() + " 条数据");
}
public void update(View view) {
User where = new User();
where.setName("lcty");
User user = new User("haha", "123456789");
userDao.update(user, where);
}
}
效果我就不贴了,感兴趣的伙伴可以自己敲一遍看下效果,分析完毕,欢迎交流。