本文实例分析了Android编程操作嵌入式关系型SQLite数据库的方法。分享给大家供大家参考,具体如下:
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 {
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语句,通过参数进行拼接
执行crud操作有两种方式,第一种方式自己写sql语句执行操作,第二种方式是使用SQLiteDatabase类调用响应的方法执行操作
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);//初始化数据库
}
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();
}
public void delete(Integer id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("DELETE FROM person WHERE id=?", new Object[] { id });
db.close();
}
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();
}
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;
}
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;
}
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;
}
public int getCount() {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM person", null);
cursor.moveToNext();
return cursor.getInt(0);
}
}
第二种方式示例:
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();
}
public void delete(Integer id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.delete("person", "id=?", new String[] { id.toString() });
db.close();
}
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();
}
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;
}
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;
}
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;
}
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();
}
希望本文所述对大家Android程序设计有所帮助。
您可能感兴趣的文章:php中删除、清空session的方式总结javascript中var的重要性分析Linux du命令查看文件夹大小并按降序排列linux下使用 du查看某个文件或目录占用磁盘空间的大小方法