SQLiteUtilsAndroid Sqlite 数据库操作封装
SQLiteUtils 是一个简单的基于Android的Sqlite数据库的操作封装,它有如下的好处:
-
便捷地创建表和增添表字段
-
灵活的数据类型处理
-
通过操作对象来insert或者update表记录
-
支持多种查询方式,支持多表自定义的复杂查询,支持分页查询
-
支持事务
快速开始:
1. 设计表:
@Table(name="t_user") public class UserModel { @Table.Column(name="user_id",type=Column.TYPE_INTEGER,isPrimaryKey=true) public Integer userId; @Table.Column(name="user_name",type=Column.TYPE_STRING,isNull=false) public String userName; @Table.Column(name="born_date",type=Column.TYPE_TIMESTAMP) public Date bornDate; @Table.Column(name="pictrue",type=Column.TYPE_BLOB) public byte[] pictrue; @Table.Column(name="is_login",type=Column.TYPE_BOOLEAN) public Boolean isLogin; @Table.Column(name="weight",type=Column.TYPE_DOUBLE) public Double weight; }
2. 初始化对象:
SQLiteDatabase db = context.openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); DbSqlite dbSqlite = new DbSqlite(db); IBaseDao<UserModel> userDAO = DaoFactory.createGenericDao(dbSqlite, UserModel.class);
3. 创建表:
userDAO.createTable();
4. Insert 记录:
UserModel user = new UserModel(); user.userName = "darcy"; user.isLogin = true; user.weight = 60.5; user.bornDate = new Date(); byte[] picture = {0x1,0x2,0x3,0x4}; user.pictrue = picture; userDAO.insert(user);
5. Update 记录:
UserModel user = new UserModel(); user.weight = 88.0; userDAO.update(user, "user_name=?", "darcy");
6. 查询:
//单条结果查询 UserModel user = userDAO.queryFirstRecord("user_name=?", "darcy"); //一般查询 List<UserModel> userList = userDAO.query("user_name=? and weight > ?", "darcy" , "60"); //分页查询 PagingList<UserModel> pagingList = userDAO.pagingQuery(null, null, 1, 3);
7. 事务支持:
DBTransaction.transact(mDb, new DBTransaction.DBTransactionInterface() { @Override public void onTransact() { // to do } };
8. 更新表(目前只支持添加字段)
@Table(name="t_user" , version=2) //修改表版本 public class UserModel { //members above... //new columns @Table.Column(name="new_column_1",type=Column.TYPE_INTEGER) public Integer newColumn; @Table.Column(name="new_column_2",type=Column.TYPE_INTEGER) public Integer newColumn2; } userDAO.updateTable();
缺点和不足:
-
还没支持多对一或者一多的关系
-
没支持联合主键
-
没支持表的外键设计
-
其他...
实例:
SqliteLookup(Android内查看Sqlite数据库利器): https://github.com/YeDaxia/SqliteLookup
评论