转自http://blog.csdn.net/furongkang/article/details/6818243
SQLite特点
1.Android平台中嵌入了一个关系型数据库SQLite,和其他数据库不同的是SQLite存储数据时不区分类型
例如一个字段声明为Integer类型,我们也可以将一个字符串存入,一个字段声明为布尔型,我们也可以存入浮点数。
除非是主键被定义为Integer,这时只能存储64位整数
2.创建数据库的表时可以不指定数据类型,例如:
CREATE TABLEperson(id INTEGER PRIMARY KEY, name)
3.SQLite支持大部分标准SQL语句,增删改查语句都是通用的,分页查询语句和MySQL相同
SELECT * FROMperson LIMIT 20 OFFSET 10
SELECT * FROMperson LIMIT 20,10
创建数据库
1.定义类继承SQLiteOpenHelper
2.声明构造函数,4个参数
3.重写onCreate()方法
4. 重写upGrade()方法
示例:
- package cn.itcast.sqlite;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- public class DBOpenHelper extends SQLiteOpenHelper {
- /**
- * 创建OpenHelper
- * @param context 上下文
- * @param name 数据库名
- * @param factory 游标工厂
- * @param version 数据库版本, 不要设置为0, 如果为0则会每次都创建数据库
- */
- public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
- super(context, name, factory, version);
- }
- /**
- * 当数据库第一次创建的时候被调用
- */
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name)");
- }
- /**
- * 当数据库版本发生改变的时候被调用
- */
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- db.execSQL("ALTER TABLE person ADD balance");
- }
- }
- public void testCreateDB() {
- DBOpenHelper helper = new DBOpenHelper(getContext(), "itcast.db", null, 2);
- helper.getWritableDatabase(); // 创建数据库
- }
CRUD操作
1.和JDBC访问数据库不同,操作SQLite数据库无需加载驱动,不用获取连接,直接可以使用
获取SQLiteDatabase对象之后通过该对象直接可以执行SQL语句
SQLiteDatabase.execSQL()
SQLiteDatabase.rawQuery()
2.getReadableDatabase()和getWritableDatabase()的区别
查看源代码后我们发现getReadableDatabase()在通常情况下返回的就是getWritableDatabase()拿到的数据库
只有在抛出异常的时候才会以只读方式打开
3.数据库对象缓存
getWritableDatabase()方法最后会使用一个成员变量记住这个数据库对象,下次打开时判断是否重用
4.SQLiteDatabase封装了insert()、delete()、update()、query()四个方法也可以对数据库进行操作
这些方法封装了部分SQL语句,通过参数进行拼接
execSQL()方法可以执行insert、delete、update和CREATETABLE之类有更改行为的SQL语句; rawQuery()方法用于执行select语句。
第一种方式示例:
- package cn.itcast.sqlite.service;
- import java.util.ArrayList;
- import java.util.List;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import cn.itcast.sqlite.DBOpenHelper;
- import cn.itcast.sqlite.domain.Person;
- public class SQLPersonService {
- private DBOpenHelper helper;
- public SQLPersonService(Context context) {
- helper = new DBOpenHelper(context, "itcast.db", null, 2);//初始化数据库
- }
- /**
- * 插入一个Person
- * @param p 要插入的Person
- */
- public void insert(Person p) {
- SQLiteDatabase db = helper.getWritableDatabase(); //获取到数据库
- db.execSQL("INSERT INTO person(name,phone,balance) VALUES(?,?)", new Object[] { p.getName(), p.getPhone() });
- db.close();
- }
- /**
- * 根据ID删除
- * @param id 要删除的PERSON的ID
- */
- public void delete(Integer id) {
- SQLiteDatabase db = helper.getWritableDatabase();
- db.execSQL("DELETE FROM person WHERE id=?", new Object[] { id });
- db.close();
- }
- /**
- * 更新Person
- * @param p 要更新的Person
- */
- public void update(Person p) {
- SQLiteDatabase db = helper.getWritableDatabase();
- db.execSQL("UPDATE person SET name=?,phone=?,balance=? WHERE id=?", new Object[] { p.getName(), p.getPhone(), p.getBalance(), p.getId() });
- db.close();
- }
- /**
- * 根据ID查找
- * @param id 要查的ID
- * @return 对应的对象, 如果未找到返回null
- */
- public Person find(Integer id) {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.rawQuery("SELECT name,phone,balance FROM person WHERE id=?", new String[] { id.toString() });
- Person p = null;
- if (cursor.moveToNext()) {
- String name = cursor.getString(cursor.getColumnIndex("name"));
- String phone = cursor.getString(1);
- Integer balance = cursor.getInt(2);
- p = new Person(id, name, phone, balance);
- }
- cursor.close();
- db.close();
- return p;
- }
- /**
- * 查询所有Person对象
- * @return Person对象集合, 如未找到, 返回一个size()为0的List
- */
- public List<Person> findAll() {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.rawQuery("SELECT id,name,phone,balance FROM person", null);
- List<Person> persons = new ArrayList<Person>();
- while (cursor.moveToNext()) {
- Integer id = cursor.getInt(0);
- String name = cursor.getString(1);
- String phone = cursor.getString(2);
- Integer balance = cursor.getInt(3);
- persons.add(new Person(id, name, phone, balance));
- }
- cursor.close();
- db.close();
- return persons;
- }
- /**
- * 查询某一页数据
- * @param page 页码
- * @param size 每页记录数
- * @return
- */
- public List<Person> findPage(int page, int size) {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.rawQuery("SELECT id,name,phone,balance FROM person LIMIT ?,?" //
- , new String[] { String.valueOf((page - 1) * size), String.valueOf(size) });
- List<Person> persons = new ArrayList<Person>();
- while (cursor.moveToNext()) {
- Integer id = cursor.getInt(0);
- String name = cursor.getString(1);
- String phone = cursor.getString(2);
- Integer balance = cursor.getInt(3);
- persons.add(new Person(id, name, phone, balance));
- }
- cursor.close();
- db.close();
- return persons;
- }
- /**
- * 获取记录数
- * @return 记录数
- */
- public int getCount() {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM person", null);
- cursor.moveToNext();
- return cursor.getInt(0);
- }
- }
第二种方式示例:
- /**
- * 插入一个Person
- * @param p 要插入的Person
- */
- public void insert(Person p) {
- SQLiteDatabase db = helper.getWritableDatabase();
- ContentValues values = new ContentValues();
- values.put("name", p.getName());
- values.put("phone", p.getPhone());
- values.put("balance", p.getBalance());
- // 第一个参数是表名, 第二个参数是如果要插入一条空记录时指定的某一列的名字, 第三个参数是数据
- db.insert("person", null, values);
- db.close();
- }
- /**
- * 根据ID删除
- * @param id 要删除的PERSON的ID
- */
- public void delete(Integer id) {
- SQLiteDatabase db = helper.getWritableDatabase();
- db.delete("person", "id=?", new String[] { id.toString() });
- db.close();
- }
- /**
- * 更新Person
- * @param p 要更新的Person
- */
- public void update(Person p) {
- SQLiteDatabase db = helper.getWritableDatabase();
- ContentValues values = new ContentValues();
- values.put("id", p.getId());
- values.put("name", p.getName());
- values.put("phone", p.getPhone());
- values.put("balance", p.getBalance());
- db.update("person", values, "id=?", new String[] { p.getId().toString() });
- db.close();
- }
- /**
- * 根据ID查找
- * @param id 要查的ID
- * @return 对应的对象, 如果未找到返回null
- */
- public Person find(Integer id) {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.query("person", new String[] { "name", "phone", "balance" }, "id=?", new String[] { id.toString() }, null, null, null);
- Person p = null;
- if (cursor.moveToNext()) {
- String name = cursor.getString(cursor.getColumnIndex("name"));
- String phone = cursor.getString(1);
- Integer balance = cursor.getInt(2);
- p = new Person(id, name, phone, balance);
- }
- cursor.close();
- db.close();
- return p;
- }
- /**
- * 查询所有Person对象
- * @return Person对象集合, 如未找到, 返回一个size()为0的List
- */
- public List<Person> findAll() {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.query("person", new String[] { "id", "name", "phone", "balance" }, null, null, null, null, "id desc");
- List<Person> persons = new ArrayList<Person>();
- while (cursor.moveToNext()) {
- Integer id = cursor.getInt(0);
- String name = cursor.getString(1);
- String phone = cursor.getString(2);
- Integer balance = cursor.getInt(3);
- persons.add(new Person(id, name, phone, balance));
- }
- cursor.close();
- db.close();
- return persons;
- }
- /**
- * 查询某一页数据
- * @param page 页码
- * @param size 每页记录数
- * @return
- */
- public List<Person> findPage(int page, int size) {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.query( //
- "person", new String[] { "id", "name", "phone", "balance" }, null, null, null, null, null, (page - 1) * size + "," + size);
- List<Person> persons = new ArrayList<Person>();
- while (cursor.moveToNext()) {
- Integer id = cursor.getInt(0);
- String name = cursor.getString(1);
- String phone = cursor.getString(2);
- Integer balance = cursor.getInt(3);
- persons.add(new Person(id, name, phone, balance));
- }
- cursor.close();
- db.close();
- return persons;
- }
- /**
- * 获取记录数
- * @return 记录数
- */
- public int getCount() {
- SQLiteDatabase db = helper.getReadableDatabase();
- Cursor cursor = db.query( //
- "person", new String[] { "COUNT(*)" }, null, null, null, null, null);
- cursor.moveToNext();
- return cursor.getInt(0);
- }
事务管理
1.使用在SQLite数据库时可以使用SQLiteDatabase类中定义的相关方法控制事务
beginTransaction() 开启事务
setTransactionSuccessful() 设置事务成功标记
endTransaction() 结束事务
2.endTransaction()需要放在finally中执行,否则事务只有到超时的时候才自动结束,会降低数据库并发效率
示例:
- public void remit(int from, int to, int amount) {
- SQLiteDatabase db = helper.getWritableDatabase();
- // 开启事务
- try {
- db.beginTransaction();
- db.execSQL("UPDATE person SET balance=balance-? WHERE id=?", new Object[] { amount, from });
- System.out.println(1 / 0);
- db.execSQL("UPDATE person SET balance=balance+? WHERE id=?", new Object[] { amount, to });
- // 设置事务标记
- db.setTransactionSuccessful();
- } finally {
- // 结束事务
- db.endTransaction();
- }
- db.close();
- }