除了可以使用文件或SharedPreferences存储数据,还可以选择使用SQLite数据库存储数据。
在Android平台上,集成了一个嵌入式关系型数据库—SQLite,
1、SQLite3支持 NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型虽然只有五种,但实际上sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型,只不过在运算或保存时会转成对应的五种数据类型。
2、SQLite最大的特点是你可以保存任何类型的数据到任何字段中,无论这列声明的数据类型是什么。例如:可以在Integer字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。
3、但有一种情况例外:定义为INTEGER PRIMARY KEY的字段只能存储64位整数, 当向这种字段中保存除整数以外的数据时,将会产生错误。
4、另外, SQLite 在解析CREATE TABLE 语句时,会忽略 CREATE TABLE 语句中跟在字段名后面的数据类型信息,如下面语句会忽略 name字段的类型信息:
CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))
SQLite可以解析大部分标准SQL语句,如:
查询语句:select * from 表名 where 条件子句 group by 分组字句 having ... order by 排序子句
如:select * from person
select * from person order by id desc
select name from person group by name having count(*)>1
分页SQL与mysql类似,下面SQL语句获取5条记录,跳过前面3条记录
select * from Account limit 5 offset 3 或者 select * from Account limit 3,5
插入语句:insert into 表名(字段列表) values(值列表)。如: insert into person(name, age) values(‘工工’,3)
更新语句:update 表名 set 字段名=值 where 条件子句。如:update person set name=‘工‘ where id=10
删除语句:delete from 表名 where 条件子句。如:delete from person where id=10
使用SQLiteDatabase操作SQLite数据库
execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句;
rawQuery()方法可以执行select语句。
使用例子如下:
SQLiteDatabase db = ....;
跟上实例:
package com.jbridge.service; import java.util.ArrayList; import java.util.Currency; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.jbridge.domain.Person; public class PersonService { private DataBaseOpenHelper dbOpenHelper; // private Context context; public PersonService(Context context) { // this.context = context; dbOpenHelper = new DataBaseOpenHelper(context); } public void save(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.beginTransaction(); database.execSQL("insert into person(name,age)values(?,?)", new Object[] { person.getName(), person.getAge() }); // database.close();可以不关闭数据库,他里面会缓存一个数据库对象,如果以后还要用就直接用这个缓存的数据库对象。但通过 // context.openOrCreateDatabase(arg0, arg1, arg2)打开的数据库必须得关闭 database.setTransactionSuccessful(); database.endTransaction(); } public void update(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.execSQL( "update person set name=?,age=? where personid=?", new Object[] { person.getName(), person.getAge(), person.getId() }); } public Person find(Integer id) { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.rawQuery( "select * from person where personid=?", new String[] { String.valueOf(id) }); if (cursor.moveToNext()) { return new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2)); } return null; } public void delete(Integer... ids) { if (ids.length > 0) { StringBuffer sb = new StringBuffer(); for (Integer id : ids) { sb.append('?').append(','); } sb.deleteCharAt(sb.length() - 1); SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.execSQL( "delete from person where personid in(" + sb.toString() + ")", ids); } } public List<Person> getScrollData(int startResult, int maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.rawQuery( "select * from person limit ?,?", new String[] { String.valueOf(startResult), String.valueOf(maxResult) }); while (cursor.moveToNext()) { persons.add(new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2))); } return persons; } // 获取分页数据,提供给SimpleCursorAdapter使用。 public Cursor getRawScrollData(int startResult, int maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); return database.rawQuery( "select personid as _id ,name,age from person limit ?,?", new String[] { String.valueOf(startResult), String.valueOf(maxResult) }); } public long getCount() { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.rawQuery("select count(*) from person", null); if (cursor.moveToNext()) { return cursor.getLong(0); } return 0; } }
package com.jbridge.service; import java.util.ArrayList; import java.util.Currency; import java.util.List; import android.R.string; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.jbridge.domain.Person; public class OtherPersonService { private DataBaseOpenHelper dbOpenHelper; // private Context context; public OtherPersonService(Context context) { // this.context = context; dbOpenHelper = new DataBaseOpenHelper(context); } public void save(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); database.insert("person", null, contentValues); } public void update(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); database.update("person", null, "personid=?", new String[] { String.valueOf(person.getId()) }); } public Person find(Integer id) { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.query("person", new String[] { "personid", "name", "age" }, "personid=?", new String[] { String.valueOf(id) }, null, null, null); if (cursor.moveToNext()) { return new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2)); } return null; } public void delete(Integer... ids) { if (ids.length > 0) { StringBuffer sb = new StringBuffer(); String[] strIds = new String[ids.length]; // for (Integer id : ids) { // sb.append('?').append(','); // } for (int i = 0; i < strIds.length; i++) { sb.append('?').append(','); strIds[i] = String.valueOf(ids[i]); } sb.deleteCharAt(sb.length() - 1); SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.delete("person", "personid in(" + sb.toString() + ")", strIds); } } public List<Person> getScrollData(int startResult, int maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.query("person", new String[] { "personid", "name", "age" }, null, null, null, null, "personid desc", startResult + "," + maxResult); while (cursor.moveToNext()) { persons.add(new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2))); } return persons; } public long getCount() { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.query("person", new String[] { "count(*)" }, null, null, null, null, null); if (cursor.moveToNext()) { return cursor.getLong(0); } return 0; } }