您的位置:首页 > 移动开发 > Android开发

Android 平台下的 SQLite 使用

2010-11-05 22:07 232 查看
SQLite 是一个非常流行嵌入式关系型数据库,之所以这么流行时因为相当小的内存占用和高速的响应,更重要的是他还是免费的。
Android 中, SQLite 是被集成于 Android runtime ,每个 Android 应用程序都可以方便的使用 SQLite 数据库。
如果你熟悉 JDBC ,那么这个掌握SQLite也就几个小时的事情。

 

 

Android为我们提供了 SQLiteOpenHelper 抽象类,只要继承它就我们就可以很方便的实现对数据库的创建及更新。SQLiteOpenHelper 抽象类两个很重要的方法onCreate和onUpdate,onCreate用于初次使用软件时创建数据库表,onUpdate用于更新修改数据库表结构。

当调用数据库SQLiteOpenHelper 实例的getWritableDatabase (或getReadableDatabase) 时,android会通过openOrCreateDatabase判断数据库是否存在,如果不存在的,会调用onCeate方法创建数据;如果数据库存在,则会通过判断数据库版本号是否执行onUpdate方法,下面是 抽象类 SQLiteOpenHelper 的部分源码,细看就知道其中的原理了

 

/**
* Create and/or open a database that will be used for reading and writing.
* Once opened successfully, the database is cached, so you can call this
* method every time you need to write to the database.  Make sure to call
* {@link #close} when you no longer need it.
*
* <p>Errors such as bad permissions or a full disk may cause this operation
* to fail, but future attempts may succeed if the problem is fixed.</p>
*
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
return mDatabase;  // The database is already open for business
}

if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}

// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock.  To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.

boolean success = false;
SQLiteDatabase db = null;
if (mDatabase != null) mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}

int version = db.getVersion();
if (version != mNewVersion) {
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}

onOpen(db);
success = true;
return db;
} finally {
mIsInitializing = false;
if (success) {
if (mDatabase != null) {
try { mDatabase.close(); } catch (Exception e) { }
mDatabase.unlock();
}
mDatabase = db;
} else {
if (mDatabase != null) mDatabase.unlock();
if (db != null) db.close();
}
}
}


 

 

 

 数据库操作工具类代码,继承SQLiteOpenHelper 抽象类,实现数据库的创建和更新。

 

package cn.dreamlist.service;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper {

public DBOpenHelper(Context context) {
/**
* 父类构造器中4个参数
*
* 1.上下文context
* context to use to open or create the database
*
* 2.数据库名,null 内存数据库
* name of the database file, or null for an in-memory database
*
* 3.游标工厂,默认为null
* factory to use for creating cursor objects, or null for the default
*
* 4.数据库版本号,如果版本号非0,且和之前的版本号不相同,则执行onUpgrade方法.
* version number of the database (starting at 1); if the database is older, onUpgrade will be used to upgrade the database
*/
super(context,"dreamlist.db", null, 1);
}

/**
* 创建数据库表
*/
@Override
public void onCreate(SQLiteDatabase db) {
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");
}

}


 

 

 

下面我们创建PersonService 类,实现对dreamlist.db 数据库的增删改查操作,当然SQLiteDatabase 类还给我们提供了写好的update,insert... 等方法,我们这里用rawQuery 和execSQL 方法加SQL语句实现了,代码看起来更加容易理解。

详细见下面代码

 

package cn.dreamlist.service;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.dreamlist.domain.Person;

public class PersonService {
private DBOpenHelper dbOpenHelper;

public PersonService(Context context) {
dbOpenHelper = new DBOpenHelper(context);
}

/**
* 保存用户
* @param person
*/
public void save(Person person) {
//获取SQLiteDatabase对象
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

db.execSQL("insert into person(name,phone) values(?,?)", new Object[] {
person.getName(), person.getPhone() });
// db.close(); 考虑到性能,这里db不用关闭,因为只有本应用才使用数据库
}
/**
* 更新用户
* @param person
*/
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() }
);

}

/**
* 通过ID, 查找用户
*/
public Person find(Integer id) {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
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);
}
return null;
}

/**
* 通过ID, 删除用户
* @param id
*/
public void delete(Integer id) {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("delete from person where personid=?", new Object[] { id });
}
/**
* 获取所有用户记录数
* @return
*/
public long getCount() {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select count(*) from person", null);
cursor.moveToFirst();
return cursor.getLong(0);
}

/**
* 获取从offset开始的,maxResult条person记录
* @return
*/
public List<Person> getScrollData(int offset, int maxResult) {
List<Person> persons = new ArrayList<Person>();

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"select * from person limit ?,?",
new String[] { String.valueOf(offset),
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"));
Person person = new Person(personId,name, phone);
persons.add(person);
}
return persons;
}

/**
* 获取所有的person记录
* @return
*/
public List<Person> getAllPerson() {
List<Person> persons = new ArrayList<Person>();

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"select * from person ", null);
while (cursor.moveToNext()) {
int personId = cursor.getInt(cursor.getColumnIndex("personid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
Person person = new Person(personId,name, phone);
persons.add(person);
}
return persons;
}
}


 

 

JavaBean Person类代码如下:

 

package cn.dreamlist.domain;

public class Person {
private Integer id;
private String name;
private String phone;

public Person() {
}

public Person(String name, String phone) {
this.name = name;
this.phone = phone;
}

public Person(Integer id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息