1、SQLite特点 1.Android平台中嵌入了一个关系型数据库SQLite,和其他数据库不同的是SQLite存储数据时不区分类型 例如一个字段声明为Integer类型,我们也可以将一个字符串存入,一个字段声明为布尔型,我们也可以存入浮点数. 除非是主键被定义为Integer,这时只能存储64位整数 2.创建数据库的表时可以不指定数据类型,例如: CREATE TABLEperson(id INTEGER PRIMARY KEY, name) 3.SQLite支持大部分标准SQL语句,增删改查语句都是通用的,分页查询语句和MySQL相同 SELEC
2、T * FROMperson LIMIT 20 OFFSET 10 SELECT * FROMperson LIMIT 20,10 创建数据库 1.定义类继承SQLiteOpenHelper 2.声明构造函数,4个参数 3.重写onCreate()方法 4. 重写upGrade()方法 java代码: 1 import Android.content.Context; 2 import android.database.sqlite.SQLiteDatabase; 3 import android.database.sqlite.SQLi
3、teOpenHelper; 4 import android.database.sqlite.SQLiteDatabase.CursorFactory; 5 6 7 public class DBOpenHelper extends SQLiteOpenHelper { 8 /** 9 * 创建OpenHelper 10 * @param context 上下文 11 * @param name 数据库名 12 * @param factory 游标工厂 13 * @param version 数据库版本, 不要设置为0, 如果为0则会每次都创建数据库 14 */ 15
4、 public DBOpenHelper(Context context, String name, CursorFactory factory, int version) { 16 super(context, name, factory, version); 17 } 18 /** 19 * 当数据库第一次创建的时候被调用 20 */ 21 public void onCreate(SQLiteDatabase db) { 22 db.execSQL("CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name
5、)"); 23 } 24 /** 25 * 当数据库版本发生改变的时候被调用 26 */ 27 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 28 db.execSQL("ALTER TABLE person ADD balance"); 29 } 30 } 31 public void testCreateDB() { 32 DBOpenHelper helper = new DBOpenHelper(getContext(), "itcast.db", null, 2
6、); 33 helper.getWritableDatabase(); // 创建数据库 34 } CRUD操作 1.和JDBC访问数据库不同,操作SQLite数据库无需加载驱动,不用获取连接,直接可以使用 获取SQLiteDatabase对象之后通过该对象直接可以执行SQL语句 SQLiteDatabase.execSQL() SQLiteDatabase.rawQuery() 2.getReadableDatabase()和getWritableDatabase()的区别 查看源代码后我们发现getReadab
7、leDatabase()在通常情况下返回的就是getWritableDatabase()拿到的数据库 只有在抛出异常的时候才会以只读方式打开 3.数据库对象缓存 getWritableDatabase()方法最后会使用一个成员变量记住这个数据库对象,下次打开时判断是否重用 4.SQLiteDatabase封装了insert()、delete()、update()、query()四个方法也可以对数据库进行操作 这些方法封装了部分SQL语句,通过参数进行拼接 执行crud操作有两种方式,第一种方式自己写sql语句执行操作,第二种方式是使用
8、SQLiteDatabase类调用响应的方法执行操作 execSQL()方法可以执行insert、delete、update和CREATETABLE之类有更改行为的SQL语句; rawQuery()方法用于执行select语句. java代码: 1 import java.util.ArrayList; 2 import java.util.List; 3 import Android.content.Context; 4 import Android.database.Cursor; 5 import Android.database.sqlite.SQLiteDa
9、tabase; 6 7 import cn.itcast.sqlite.DBOpenHelper; 8 import cn.itcast.sqlite.domain.Person; 9 public class SQLPersonService { 10 11 private DBOpenHelper helper; 12 13 public SQLPersonService(Context context) { 14 helper = new DBOpenHelper(context, "itcast.db", null, 2);//初始化数据库 15 } 16 17
10、 /** 18 * 插入一个Person 19 * @param p 要插入的Person 20 */ 21 public void insert(Person p) { 22 SQLiteDatabase db = helper.getWritableDatabase(); //获取到数据库 23 db.execSQL("INSERT INTO person(name,phone,balance) VALUES(?,?)", new Object[] { p.getName(), p.getPhone() }); 24 db.close(); 25 } 26 27 /**
11、 28 * 根据ID删除 29 * @param id 要删除的PERSON的ID 30 */ 31 public void delete(Integer id) { 32 SQLiteDatabase db = helper.getWritableDatabase(); 34. db.execSQL("DELETE FROM person WHERE id=?", new Object[] { id }); 35. db.close(); 33 } 34 /** 35 * 更新Person 36 * @param p 要更新的Person 37 */ 38 public
12、 void update(Person p) { 39 SQLiteDatabase db = helper.getWritableDatabase(); 40 db.execSQL("UPDATE person SET name=?,phone=?,balance=? WHERE id=?", new Object[] { 41 p.getName(), p.getPhone(), p.getBalance(), p.getId() }); 42 db.close(); 43 } 44 45 /** 46 * 根据ID查找 47 * @param id 要查的ID 48
13、 @return 对应的对象, 如果未找到返回null 49 */ 50 51 public Person find(Integer id) { 52 SQLiteDatabase db = helper.getReadableDatabase(); 53 Cursor cursor = db.rawQuery("SELECT name,phone,balance FROM person WHERE id=?", new String[] { id.toString() }); 54 Person p = null; 55 if (cursor.moveToNext()) {
14、 56 String name = cursor.getString(cursor.getColumnIndex("name")); 57 String phone = cursor.getString(1); 58 Integer balance = cursor.getInt(2); 59 p = new Person(id, name, phone, balance); 60 } 61 cursor.close(); 62 db.close(); 63 return p; 64 } 65 /** 66 * 查询所有Person对象 67 * @return Pers
15、on对象集合, 如未找到, 返回一个size()为0的List
68 */
69
70 public List
16、{ 75 Integer id = cursor.getInt(0); String name = cursor.getString(1); 76 String phone = cursor.getString(2); 77 Integer balance = cursor.getInt(3); 78 persons.add(new Person(id, name, phone, balance)); 79 } 80 cursor.close(); 81 db.close(); 82 return persons; 83 } 84 85 /** 86 * 查询某一页数据
17、
87 * @param page 页码
88 * @param size 每页记录数
89 * @return
90 */
91 public List
18、e - 1) * size), String.valueOf(size) });
94 List
19、dd(new Person(id, name, phone, balance)); 102 } 103 cursor.close(); 104 db.close(); 105 return persons; 106 } 107 108 /** 109 * 获取记录数 110 * @return 记录数 111 */ 112 public int getCount() { 113 SQLiteDatabase db = helper.getReadableDatabase(); 114 Cursor cursor = db.rawQuery("SELECT COUNT(
20、) FROM person", null); 115 cursor.moveToNext(); 116 return cursor.getInt(0); 117 } 118 } 1 /** 2 * 插入一个Person 3 * @param p 要插入的Person 4 */ 5 public void insert(Person p) { 6 SQLiteDatabase db = helper.getWritableDatabase(); 7. 7 ContentValues values = new ContentValues(); 8 values.put("
21、name", p.getName()); 9 values.put("phone", p.getPhone()); 10 values.put("balance", p.getBalance()); 11 // 第一个参数是表名, 第二个参数是如果要插入一条空记录时指定的某一列的名字, 第三个参数是数据 12 db.insert("person", null, values); 13 db.close(); 14 } 15 /** 16 * 根据ID删除 17 * @param id 要删除的PERSON的ID 18 */ 19 public void delete(In
22、teger id) { 20 SQLiteDatabase db = helper.getWritableDatabase(); 21 db.delete("person", "id=?", new String[] { id.toString() }); 22 db.close(); 23 } 24 /** 25 * 更新Person 26 * @param p 要更新的Person 27 */ 28 public void update(Person p) { 29 SQLiteDatabase db = helper.getWritableDatabase();
23、 30 ContentValues values = new ContentValues(); 31 values.put("id", p.getId()); 32 values.put("name", p.getName()); 33 values.put("phone", p.getPhone()); 34 values.put("balance", p.getBalance()); 35 db.update("person", values, "id=?", new String[] { p.getId().toString() }); 36 db.close(); 3
24、7 } 38 /** 39 * 根据ID查找 40 * @param id 要查的ID 41 * @return 对应的对象, 如果未找到返回null 42 */ 43 public Person find(Integer id) { 44 SQLiteDatabase db = helper.getReadableDatabase(); 45 Cursor cursor = db.query("person", new String[] { "name", "phone", "balance" }, "id=?", new String[] { id.toString()
25、 }, null, null, null); 46 Person p = null; 47 if (cursor.moveToNext()) { 48 String name = cursor.getString(cursor.getColumnIndex("name")); 49 String phone = cursor.getString(1); 50 Integer balance = cursor.getInt(2); 51 p = new Person(id, name, phone, balance); 52 } 53 cursor.close(); 54
26、db.close();
55 return p;
56 }
57 /**
58 * 查询所有Person对象
59 * @return Person对象集合, 如未找到, 返回一个size()为0的List
60 */
61 public List
27、 null, null, null, "id desc");
64 List
28、on(id, name, phone, balance));
72 }
73 cursor.close();
74 db.close();
75 return persons;
76 }
77 /**
78 * 查询某一页数据
79 * @param page 页码
80 * @param size 每页记录数
81 * @return
82 */
83 public List
29、Cursor cursor = db.query( "person", new String[] { "id", "name", "phone", "balance" }, null, null, null, null, null, (page - 1) * size + "," + size);
86 List
30、tring(1); 90 String phone = cursor.getString(2); 91 Integer balance = cursor.getInt(3); 92 persons.add(new Person(id, name, phone, balance)); 93 } 94 cursor.close(); 95 db.close(); 96 return persons; 97 } 98 /** 99 * 获取记录数 100 * @return 记录数 101 */ 102 public int getCount() { 103 SQLite
31、Database db = helper.getReadableDatabase(); 104 Cursor cursor = db.query( // "person", new String[] { "COUNT(*)" }, null, null, null, null, null); 105 cursor.moveToNext(); 106 return cursor.getInt(0); 107 } 事务管理 1.使用在SQLite数据库时可以使用SQLiteDatabase类中定义的相关方法控制事务 beginTransaction() 开启事务
32、 setTransactionSuccessful() 设置事务成功标记 endTransaction() 结束事务 2.endTransaction()需要放在finally中执行,否则事务只有到超时的时候才自动结束,会降低数据库并发效率 java代码: 1 public void remit(int from, int to, int amount) { 2 SQLiteDatabase db = helper.getWritableDatabase(); 3. 3 // 开启事务 4 try { 5 db.beginTransaction(); 6 db
33、execSQL("UPDATE person SET balancebalance=balance-? WHERE id=?", new Object[] { amount, from }); 7 System.out.println(1 / 0); 8 db.execSQL("UPDATE person SET balancebalance=balance+? WHERE id=?", new Object[] { amount, to }); 9 // 设置事务标记 10 db.setTransactionSuccessful(); 11 } finally { 12 // 结束事务 13 db.endTransaction(); 14 } 15 db.close(); 16 } 35






