Android Sqlite 工具类封装

鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用。

该封装类主要支持一下功能

  1. 支持多用户数据储存
  2. 支持 Sqlite数据库升级
  3. 支持传入 Sql 语句建表
  4. 支持 SQLiteDatabase 基本操作。比如:execSQL、rawQuery、insert等等
  5. 解决了数据库并发问题
      

先贴上封装类代码

/**
 * 
 * @ClassName: DataBaseOpenHelper
 * @Description: 数据库工具类
 * @author lhy
 * @date 2014-10-9 下午2:36:41
 * 
 */
public class DataBaseOpenHelper extends SQLiteOpenHelper {
	private static Map<String, DataBaseOpenHelper> dbMaps = new HashMap<String, DataBaseOpenHelper>();
	private OnSqliteUpdateListener onSqliteUpdateListener;
	/**
	 * 建表语句列表
	 */
	private List<String> createTableList;
	private String nowDbName;

	private DataBaseOpenHelper(Context context, String dbName, int dbVersion, List<String> tableSqls) {
		super(context, dbName, null, dbVersion);
		nowDbName = dbName;
		createTableList = new ArrayList<String>();
		createTableList.addAll(tableSqls);
	}

	/**
	 * 
	 * @Title: getInstance
	 * @Description: 获取数据库实例
	 * @param @param context
	 * @param @param userId
	 * @param @return
	 * @return DataBaseOpenHelper
	 * @author lihy
	 */
	public static DataBaseOpenHelper getInstance(Context context, String dbName, int dbVersion, List<String> tableSqls) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(dbName);
		if (dataBaseOpenHelper == null) {
			dataBaseOpenHelper = new DataBaseOpenHelper(context, dbName, dbVersion, tableSqls);
		}
		dbMaps.put(dbName, dataBaseOpenHelper);
		return dataBaseOpenHelper;
	};

	@Override
	public void onCreate(SQLiteDatabase db) {
		for (String sqlString : createTableList) {
			db.execSQL(sqlString);
		}
	}
	
	/**
	 * 
	 * @Title: execSQL
	 * @Description: Sql写入
	 * @param @param sql
	 * @param @param bindArgs
	 * @return void
	 * @author lihy
	 */
	public void execSQL(String sql, Object[] bindArgs) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
			database.execSQL(sql, bindArgs);
		}
	}

	/**
	 * 
	 * @Title: rawQuery
	 * @Description:
	 * @param @param sql查询
	 * @param @param bindArgs
	 * @param @return
	 * @return Cursor
	 * @author lihy
	 */
	public Cursor rawQuery(String sql, String[] bindArgs) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
			Cursor cursor = database.rawQuery(sql, bindArgs);
			return cursor;
		}
	}

	/**
	 * 
	 * @Title: insert
	 * @Description: 插入数据
	 * @param @param table
	 * @param @param contentValues 设定文件
	 * @return void 返回类型
	 * @author lihy
	 * @throws
	 */
	public void insert(String table, ContentValues contentValues) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
			database.insert(table, null, contentValues);
		}
	}

	/**
	 * 
	 * @Title: update
	 * @Description: 更新
	 * @param @param table
	 * @param @param values
	 * @param @param whereClause
	 * @param @param whereArgs 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public void update(String table, ContentValues values, String whereClause, String[] whereArgs) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
			database.update(table, values, whereClause, whereArgs);
		}
	}
	/**
	 * 
	 * @Title: delete
	 * @Description:删除
	 * @param @param table
	 * @param @param whereClause
	 * @param @param whereArgs
	 * @return void
	 * @author lihy
	 */
	public void delete(String table, String whereClause, String[] whereArgs) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
			database.delete(table, whereClause, whereArgs);
		}
	}

	/**
	 * 
	 * @Title: query
	 * @Description: 查
	 * @param @param table
	 * @param @param columns
	 * @param @param selection
	 * @param @param selectionArgs
	 * @param @param groupBy
	 * @param @param having
	 * @param @param orderBy
	 * @return void
	 * @author lihy
	 */
	public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having,
			String orderBy) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
			// Cursor cursor = database.rawQuery("select * from "
			// + TableName.TABLE_NAME_USER + " where userId =" + userId, null);
			Cursor cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
			return cursor;
		}
	}
	/**
	 * 
	 * @Description:查
	 * @param table
	 * @param columns
	 * @param selection
	 * @param selectionArgs
	 * @param groupBy
	 * @param having
	 * @param orderBy
	 * @param limit
	 * @return
	 * Cursor
	 * @exception:
	 * @author: lihy
	 * @time:2015-4-3 上午9:37:29
	 */
	public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having,
			String orderBy,String limit) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
			// Cursor cursor = database.rawQuery("select * from "
			// + TableName.TABLE_NAME_USER + " where userId =" + userId, null);
			Cursor cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
			return cursor;
		}
	}

	/**
	 * 
	 * @Description 查询,方法重载,table表名,sqlString条件
	 * @param @return
	 * @return Cursor
	 * @author lihy
	 */
	public Cursor query(String tableName, String sqlString) {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		synchronized (dataBaseOpenHelper) {
			SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
			Cursor cursor = database.rawQuery("select * from " + tableName + " " + sqlString, null);

			return cursor;
		}
	}

	/**
	 * @see android.database.sqlite.SQLiteOpenHelper#close()
	 */
	public void clear() {
		DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
		dataBaseOpenHelper.close();
		dbMaps.remove(dataBaseOpenHelper);
	}

	/**
	 * onUpgrade()方法在数据库版本每次发生变化时都会把用户手机上的数据库表删除,然后再重新创建。<br/>
	 * 一般在实际项目中是不能这样做的,正确的做法是在更新数据库表结构时,还要考虑用户存放于数据库中的数据不会丢失,从版本几更新到版本几。(非
	 * Javadoc)
	 * 
	 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
	 *      .SQLiteDatabase, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		if (onSqliteUpdateListener != null) {
			onSqliteUpdateListener.onSqliteUpdateListener(db, arg1, arg2);
		}
	}

	public void setOnSqliteUpdateListener(OnSqliteUpdateListener onSqliteUpdateListener) {
		this.onSqliteUpdateListener = onSqliteUpdateListener;
	}
}

 数据库更新接口代码

public interface OnSqliteUpdateListener {
	public void onSqliteUpdateListener(SQLiteDatabase db, int oldVersion, int newVersion);
}

 

转载于:https://www.cnblogs.com/ProMonkey/p/5765616.html

大家好,个人觉得用Sqlite数据库时,经常需要进行机械性的CRUD操作,故对其进行了一下封装,希望能起到抛砖引玉的作用。 目的:封装共有的CRUD 下面简单的说一下使用步骤,如果觉得多余,可以无视。 1. 实现自己的DBHelper: /** * * @author Kee.Li * * 1. 继承了SmartDBHelper,不需要重写SQLiteOpenHelper的那两个方法 * 2. 父类构造方法参数modelClasses是实体类的数组,也就是需要生产表的类的Class数组 * */ public class DBHelper extends SmartDBHelper { //数据库名称 private final static String DATABASE_NAME = "books.db"; //数据库版本 private final static int DATABASE_VERSION = 2; //需要生成数据库表的类的数组 private final static Class<?>[] modelClasses = {Book.class,User.class}; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION,modelClasses); } } 2.创建app需要的实体,也就是对应的数据库表(这里的实体添加到DBHelper的modelClasses数组中) /** * 数据库的实体 * @author Kee.Li * 关于注解: * Table: 此类对应的数据库表名 * Id:标识此属性为数据库自增长的id,应为int型 * Column:标识此属性对应的数据库字段名 */ @Table(name="t_books") public class Book{ @Id @Column(name="book_id") private int bookId; @Column(name="book_name") private String bookName; @Column(name="book_author") private String bookAuthor; //set get 方法省略.... } 3. 实现DAO,也就是对实体的CRUD类 /** * @author Kee.Li * * 此类只需要继承TemplateDAO,在构造方法里面给父类的属性dbHelper赋值,即可实现CRUD操作 * 若有复杂的操作,可以自定义方法 */ public class BookDAO extends TemplateDAO { /** * 创建DAO时初始化连接数据库对象helper * @param context */ public BookDAO(Context context) { super(new DBHelper(context)); } } 4. activity的调用 bookDAO = new BookDAO(this); List books = bookDAO.find(); 好了,到此结束,如果有什么好的建议或者意见,希望可以共同学习!谢谢大家!
一个简单的基于AndroidSqlite数据库的操作封装,它有如下的好处:便捷地创建表和增添表字段灵活的数据类型处理通过操作对象来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 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 userList = userDAO.query("user_name=? and weight > ?", "darcy" , "60"); //分页查询 PagingList 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 标签:SQLiteUtils
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值