Android开发笔记(三十一)SQLite游标及其数据结构

来源:互联网 发布:ubuntu下载地址 编辑:程序博客网 时间:2024/06/05 04:45

ContentValues

ContentValues类似于映射,也是用于存储键值对。区别之处在于ContentValues的键只能是字符串,查看ContentValues的源码,会发现其内部保存键值对的数据结构就是HashMap,“private HashMap<String, Object> mValues;”。另外,ContentValues实现了Parcelable接口,也是为了提高手机上的处理效率。


这里提到ContentValues,还是因为Android源码在操作SQLite时只认这个数据结构,而不认别的java容器类,所以我们得额外对它加以了解了。幸好ContentValues的用法很简单,主要就是保存操作put,以及读取操作get。put和get方法都支持常用的基本数据类型,如整型、浮点数、字符串、布尔类型、字节等等。


SQLite在插入、更新、查询操作中需要用到ContentValues数据,下面是插入和更新的代码例子:
private static final String TABLE_NAME = "person";public int delete(String condition) {int count = mDB.delete(TABLE_NAME, condition, null);return count;}public boolean insert(ArrayList<Person> personArray) {for (int i = 0; i < personArray.size(); i++) {// ContentValues对象ContentValues cv = new ContentValues();cv.put("name", personArray.get(i).name);cv.put("age", personArray.get(i).age);cv.put("height", personArray.get(i).height);cv.put("weight", personArray.get(i).weight);cv.put("company", personArray.get(i).company);long result = mDB.insert(TABLE_NAME, "", cv);// 添加成功后返回行号,失败后返回-1if (result == -1) {return false;}}return true;}public int update(Person person, String condition) {ContentValues cv = new ContentValues();cv.put("name", person.name);cv.put("age", person.age);cv.put("height", person.height);cv.put("weight", person.weight);cv.put("company", person.company);int count = mDB.update(TABLE_NAME, cv, condition, null);return count;}


Cursor

Cursor是用来指示当前查询操作的游标,在Android中一般用于查询SQLite,也可用于查询ContentProvider,甚至可用于DownloadManager查询下载任务。Cursor的常用方法如下:


控制类
close : 关闭游标
isClosed : 判断游标是否关闭
isFirst : 判断游标是否在开头
isLast : 判断游标是否在末尾


移动类
moveToFirst : 移动游标到开头
moveToLast : 移动游标到末尾
moveToNext : 移动游标到下一个
moveToPrevious : 移动游标到上一个
move : 往后移动游标若干偏移量
moveToPosition : 移动游标到指定位置


取值类
getCount : 获取记录数
getInt : 获取当前记录的整型值
getFloat : 获取当前记录的浮点数值
getString : 获取当前记录的字符串值
getType : 获取当前记录的字段类型


下面是使用游标进行查询的代码例子:

public ArrayList<Person> query(String sql) {ArrayList<Person> personArray = new ArrayList<Person>();Cursor cursor = mDB.rawQuery(sql, null);if (cursor.moveToFirst()) {for (;; cursor.moveToNext()) {Person person = new Person();person.xuhao = cursor.getInt(0);person.name = cursor.getString(1);person.age = cursor.getInt(2);person.height = cursor.getFloat(3);person.weight = cursor.getDouble(4);person.company = cursor.getLong(5);personArray.add(person);if (cursor.isLast() == true) {break;}}}cursor.close();return personArray;}


点击下载本文用到的SQLite游标操作的工程代码



点此查看Android开发笔记的完整目录




0 0
原创粉丝点击