Android数据库CRUD操作的封装与实现

在项目中创建了两个SourceFolder。其中core文件夹下存放的都是通用代码,可以在其他项目中重复使用(当然最好是导出 jar包了)。org.dw.core.utils包下是一些工具类,所提供的都是静态方法(可以开源的)。org.dw.core.db包下就是数据库 的操作工具了。EntityDao是一个泛型接口,定义了CRUD的方法,其他实体DAO都要实现她。目前只做到这一步,下一步将利用反射实现更高级的封 装。

/**
 * 基本DAO接口
 * @author EwinLive
 *
 * @param <T>
 * @param <PK>
 */
public interface EntityDao<T, PK extends Serializable> {
 
 /**
 * 添加
 * @param entity
 */
 void save(final T entity);
 
 /**
 * 移除记录(指定ID集)
 * @param ids 可以有多个
 */
 void remove(final PK... ids);
 
 /**
 * 更新
 * @param entity
 */
 void upDate(final T entity);
 
 /**
 * 按ID查询对象
 * @param id
 * @return
 */
 T find(final PK id);
 
 /**
 * 分页查询
 * @param startResult 开始位置
 * @param maxResult 记录容量
 * @return
 */
 List<T> getScroolData(Integer startResult, Integer maxResult);
 
 /**
 * 返回记录总数
 * @return
 */
 public Long getCount();
 
} 


项目中要对消息实体”SimpleMessage”实现数据库的CRUD操作,只需要创建一个实现了”EntityDao”接口的”SimpleMessageDao”(可以观察一下包的位置)。这样做不仅可以简化代码结构,而且可以大大减少SQL语句的编写。

/**
 * 简单消息DAO
 * SQLite
 * dbHelper
 * @author EwinLive
 *
 *事务处理示例:
 		SQLiteDatabase sdb = dbHelper.getReadableDatabase();
		sdb.beginTransaction();//开启事务
		try {
			sdb.execSQL("XXXXX");
			sdb.execSQL("YYYYY");
			sdb.setTransactionSuccessful();//设置事务成功标志
		} catch (SQLException e) {
			e.printStackTrace();
		}
		sdb.endTransaction();//提交事务
 */
public class SimpleMessageDao implements EntityDao<SimpleMessage, Integer> {
	/**
	 * 表名
	 */
	public static final String TABLE = "simple_message";
 
	/**
	 * 数据库管理器
	 * 注意:dbHelper.getReadableDatabase(),会先以可读写方式访问数据库,当磁盘空间已满时会切换到只读方式。
	 */
	DataBaseHelper dbHelper;
 
	public SimpleMessageDao(Context context) {
		super();
		dbHelper = new DataBaseHelper(context);
	}
 
	@Override
	public void save(SimpleMessage entity) {
		dbHelper.getReadableDatabase().execSQL(
				"insert into "+ TABLE +"(title, content, time, accountId, consumerId) values(?,?,?,?,?)",
				new Object[]{entity.getTitle(),entity.getContent(),entity.getTime(),entity.getAccountId(),entity.getConsumerId()});
	}
 
	@SuppressWarnings("unused")
	@Override
	public void remove(Integer... ids) {
		if(ids.length > 0){
			StringBuffer sb = new StringBuffer();
			for(Integer id : ids){
				sb.append('?').append(',');
			}
			sb.deleteCharAt(sb.length() - 1);
			dbHelper.getReadableDatabase().execSQL(
					"delete from "+ TABLE +" where id in(" + sb + ")", (Object[]) ids);
		}
	}
 
	@Override
	public void upDate(SimpleMessage entity) {
		dbHelper.getReadableDatabase().execSQL(
				"update "+ TABLE +" set title=?, content=?, time=?, accountId=?, consumerId=? where id =?",
				new Object[]{entity.getTitle(),entity.getContent(),entity.getTime(),entity.getAccountId(),entity.getConsumerId(),entity.getId()});
	}
 
	@Override
	public SimpleMessage find(Integer id) {
		Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + TABLE + " where id=?",
				new String[]{String.valueOf(id)});
 
		if(cursor.moveToNext())
			return new SimpleMessage(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getInt(4),cursor.getInt(5));
		return null;
	}
 
	@Override
	public List<SimpleMessage> getScroolData(Integer startResult,
			Integer maxResult) {
 
		List<SimpleMessage> messages = new ArrayList<SimpleMessage>(0);
		Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + TABLE + " limit ?, ?",
				new String[]{String.valueOf(startResult), String.valueOf(maxResult)});
 
		while(cursor.moveToNext()){
			messages.add(new SimpleMessage(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getInt(4),cursor.getInt(5)));
		}
 
		return messages;
	}
 
	@Override
	public Long getCount() {
		Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select count(*) from " + TABLE,
				null);
 
		if(cursor.moveToNext())
			return cursor.getLong(0);
		return 0l;
	}
} 


 

这样就可以在你需要查寻数据的地方创建一个"SimpleMessageDao"对象来实现数据库的操作了。

比如要查询所有消息,并以ListView显示出来就很简单了

/**
 * 初始化消息列表
 */
public void initMessageListView(){
	ListView list = (ListView) Main.this.findViewById(R.id.message_list);
 
	//列表数据
	List<HashMap<String, String>> messageListData = new ArrayList<HashMap<String, String>>();
 
	//查询数据
	SimpleMessageDao smDao = new SimpleMessageDao(Main.this);
	List<SimpleMessage> messages = smDao.getScroolData(1, 20);
 
	//添加数据
	HashMap<String, String> message;
	for(SimpleMessage sm : messages){
		message = new HashMap<String, String>();
		message.put("id", String.valueOf(sm.getId()));
		message.put("content", sm.getContent());
		message.put("time", sm.getTime());
		messageListData.add(message);
	}
 
	//组装适配器
	SimpleAdapter adapter = new SimpleAdapter(
			Main.this,
			messageListData,
			R.layout.message_list_item,//列表条目的布局样式
			new String[]{"id", "content", "time"},//对应HashMap的Key
			new int[]{R.id.message_id, R.id.message_content, R.id.message_time});//对应TextView的id
	list.setAdapter(adapter);
 
	//设置条目监听器
	list.setOnItemClickListener(new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
			ListView listView = (ListView) parent;
			@SuppressWarnings("unchecked")
			HashMap<String, String> data = (HashMap<String, String>) listView.getItemAtPosition(position);
			Toast.makeText(Main.this,
					"ID: " + data.get("id") + " \nContent: " + data.get("content") + "\nTime: " + data.get("time"),
					Toast.LENGTH_SHORT).show();
		}
 
	});
} 


 

 

 

摘自:

http://tech.cncms.com/shouji/android/113377_2.html

 

http://disanji.net/2011/08/21/%e6%b5%85%e8%b0%88android%e6%95%b0%e6%8d%ae%e5%ba%93crud%e6%93%8d%e4%bd%9c%e7%9a%84%e5%b0%81%e8%a3%85%e4%b8%8e%e5%ae%9e%e7%8e%b0/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
大家好,个人觉得用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(); 好了,到此结束,如果有什么好的建议或者意见,希望可以共同学习!谢谢大家!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值