Android SQLite使用详解
一、SQLite简介
在Android平台中,集成了一个嵌入式关系型数据库--SQLite,它支持NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然只支持五种数据类型,实际上可以接受varchar(n),char(n),decimal(p,s)等数据类型,在进行运算或保存的时候会转换成对应的五种数据类型。
ex:可以在Integer类型的字段中存放字符串,或者在布尔类型字段中存放浮点数,或者在字符型字段中存放日期,but!定义为INTEGER PRIMARY KEY的字段只能存储64位整数,另外,在编写CREATE TABLE语句时,可以省略跟在字段名称后面的数据类型;
create table person(personid integer primary key autoincrement,name varchar(20))//name的类型可省略; select * from tablename where tiaojian group by 分组字句 having... order by 排序字句 select * from person select * from person order by id desc/asc select name from person group by name having count(*)>1
分页:select * from Account limit 5 offset 3 或者 select * from Account limit3,5
插入语句:insert into tablename(字段列表) values(值列表)
insert into person(name,age) values("Livingstone",22)
更新语句:update tablename set field1=val1,field2=val2 where 条件语句
update person set name="Livingstone" where id = 10
删除语句:delete from tablename where 条件语句
delete from person where id=10
获取添加记录后自增长的ID值:select last_insert_rowid()
SQLiteDatabase专门提供了对于添加、删除、更新、查询的操作方法:insert(),delete(),update()和query();
insert()方法用于添加数据,各个字段的数据使用ContentValues进行存放,ContentValues类似于MAP,相对于MAP,它提供了存取数据对应的put(String key,Xxx value)和getAsXxx(String key)方法;
long rowid=db.insert("person",null,values);//返回新添记录的行号,与主键id无关;
不管第三个参数是否包含数据,执行Insert()方法必然添加一条记录,如果第三个参数为空,会添加一条除主键之外
其他字段值为Null的记录,Insert()方法内部其实是通过构造SQL语句完成数据的添加,第二个参数用于指定空值字段的名称:如果第三个参数values为Null或者元素个数为0,由于Insert()方法要求必须添加一条除了主键之外其它字段为Null值的记录,为了满足SQL语法要求,insert语句必须给定一个字段名,ex:insert into person(name) values(NULL),若不给字段名,insert语句就为:insert into person() values(),对于字段名,建议使用主键之外的字段,如果使用了INTEGER类型的主键字段,执行类似insert into person(personid) values(NULL)的insert语句后,该主键字段值也不会为NULL,若第三个参数values不为Null并且元素个数大于0,第二个参数设置为null。
2、SQLite使用
public class DBOpenHelper extends SQLiteOpenHelper { // 类没有实例化,不能用作父类构造器的参数,必须声明为静态 public DBOpenHelper(Context context, int version) { super(context, "SQLite.db", null, version); // 第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null代表使用系统默认的游标工厂; } @Override public void onCreate(SQLiteDatabase db) {// 数据库第一次被创建的时候被调用,最开始创建数据库时赋的版本号值是0 // SQLiteDatabase用于生成数据库表;数据库存放路径:<package name>/databases/ db.execSQL("create table person(personid integer primary key autoincrement, name varchar(20))"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// 版本号升级的时候进行调用;如果数据库不存在就不调用 db.execSQL("alter table person add phone varchar(12) null");// 往表中增加一列 } }
数据库辅助类使用
DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext(), 1); dbOpenHelper.getWritableDatabase();// 会create数据库表or/open数据库表
下面是两个数据库操作类,实现数据库操作基本的CRUD以及数据分页
public class PersonService { private DBOpenHelper dbOpenHelper; public PersonService(Context context) { super(); this.dbOpenHelper = new DBOpenHelper(context, 2); } public void save(Person person) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); // SQLiteDatabase db2 = dbOpenHelper.getWritableDatabase();有缓存的功能,同一个Helper用此方法得到的对象为db; db.execSQL("insert into person(name,phone) values(?,?)", new Object[] {person.getName(), person.getPhone() }); } public void delete(Integer id) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from person where personid=?", new Object[] { id }); } public void update(Person person) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("update person set name=?,phone=? where personid=?",new Object[] { person.getName(), person.getPhone(),person.getId() }); } public Person find(Integer id) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); // 如果数据库磁盘空间未满,得到的实例即为getWritableDatabase()得到的对象;因为此方法会调用getWritableDatabase方法; Cursor cursor = db.rawQuery("select * from person where personid=?",new String[] { id.toString() }); if (cursor.moveToFirst()) { int personid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); return new Person(personid, name, phone); } cursor.close(); return null; } /* * 获取分页数据 */ public List getScollData(int offest, int maxResult) { List persons = new ArrayList(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from person order by personid asc limit ?,?",new String[] { String.valueOf(offest),String.valueOf(maxResult) }); while (cursor.moveToNext()) { int personid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); persons.add(new Person(personid, name, phone)); } cursor.close(); return persons; } public long getCount() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select count(*) from person", null); cursor.moveToFirst(); long result = cursor.getLong(0); return result; } }
public class OtherPersonService { private DBOpenHelper dbOpenHelper; public OtherPersonService(Context context) { super(); this.dbOpenHelper = new DBOpenHelper(context, 2); } public void save(Person person) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues();// ContentValues 专门用于保存字段的值 values.put("name", person.getName()); values.put("phone", person.getPhone()); db.insert("person", null, values);// 第三个参数为字段值,第二个参数为空值字段,如果第三个参数为null } public void delete(Integer id) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.delete("person", "personid=?", new String[] { id.toString() }); } public void update(Person person) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", person.getName()); values.put("phone", person.getPhone()); db.update("person", values, "personid=?", new String[] { person.getId().toString() }); } public Person find(Integer id) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.query("person", null, "personid=?",new String[] { id.toString() }, null, null, null); if (cursor.moveToFirst()) { int personid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); return new Person(personid, name, phone); } cursor.close(); return null; } /* * 获取分页数据 */ public List getScollData(int offest, int maxResult) { List persons = new ArrayList(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.query("person", null, null, null, null, null,"personid asc", offest + "," + maxResult); //db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); while (cursor.moveToNext()) { int personid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); persons.add(new Person(personid, name, phone)); } cursor.close(); return persons; } public long getCount() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.query("person", new String[] { "count(*)" }, null, null, null, null, null); //db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); cursor.moveToFirst(); long result = cursor.getLong(0); return result; } }
两个类实现的功能相同,前面一个类是自己写SQL语句实现,后面是采用SQLiteDatabase的方法进行数据操作;
三、SQLite实现事务
public void payment() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); db.beginTransaction();//开始事务 try { db.execSQL("update person set amount=amount-10 where personid=2"); db.execSQL("update person set amount=amount+10 where personid=5"); db.setTransactionSuccessful();// 设置事务的标志为true,调用此方法会在执行到endTransaction()方法是提交事务,若没有调用此方法会在执行到endTransaction()方法回滚事务。 } catch (SQLException e) { } finally { db.endTransaction(); } // 结束事务,有两种情况:commit,rollback, // 事务的提交或回滚是由事务的标志决定的,如果事务的标志为true就会提交,否则回滚,默认情况下事务的标志为false }
PS:类似转账功能,两个操作在同一个事务中完成。