在操作之前,朋友们要先下载SQLite数据库,官方的下载页面是,我是在Windows下试验,所以我选择了Precompiled Binaries For Windows下面的sqlite-shell-win32-x86和sqlite-analyzer-win32-x86的zip包,前者是SQLite数据库引擎,后者是SQLite数据库分析器,主要用于分析数据库的状态等信息,大家也可以根据自己的情况去下载。下载完成后分别解压,得到两个可执行文件,如图:
D:\>sqlite3 test.db
SQLite version 3.7.7.1 2011-06-28 17:39:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .databases
seq name file
--- --------------- ----------------------------------------------------------
0 main D:\test.db
sqlite>
sqlite> CREATETABLE person (id INTEGERPRIMARYKEY AUTOINCREMENT, nameVARCHAR(20), age SMALLINT);
sqlite> .tables
person
sqlite> .schema person
CREATETABLE person (id INTEGERPRIMARYKEY AUTOINCREMENT, nameVARCHAR(20), age SMALLINT);
sqlite>
sqlite> CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), age SMALLINT);
sqlite> .tables
person
sqlite> .schema person
CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), age SMALLINT);
sqlite>
D:\>sqlite3_analyzer test.db
/** Disk-Space Utilization Report For test.db
Page size in bytes.................... 1024
Pages in the whole file (measured).... 4
Pages in the whole file (calculated).. 4
Pages that store data................. 4 100.0%
Pages on the freelist (per header).... 0 0.0%
Pages on the freelist (calculated).... 0 0.0%
Pages of auto-vacuum overhead......... 0 0.0%
Number of tables in the database...... 4
Number of indices..................... 0
Number of named indices............... 0
Automatically generated indices....... 0
Size of the file in bytes............. 4096
Bytes of user payload stored.......... 39 0.95%
...
CREATETABLE person (id INTEGERPRIMARYKEY AUTOINCREMENT, nameVARCHAR(20), age SMALLINT);
INSERTINTO"person"VALUES(1,'john',30);
INSERTINTO"person"VALUES(2,'david',35);
INSERTINTO"person"VALUES(3,'henry',40);
DELETEFROM sqlite_sequence;
INSERTINTO"sqlite_sequence"VALUES('person',3);
COMMIT;
sqlite> .output dump.sql
sqlite> .dump
sqlite>
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), age SMALLINT);
INSERT INTO "person" VALUES(1,'john',30);
INSERT INTO "person" VALUES(2,'david',35);
INSERT INTO "person" VALUES(3,'henry',40);
DELETE FROM sqlite_sequence;
INSERT INTO "sqlite_sequence" VALUES('person',3);
COMMIT;
sqlite> .output dump.sql
sqlite> .dump
sqlite>
CREATETABLE person (id INTEGERPRIMARYKEY AUTOINCREMENT, nameVARCHAR(20), age SMALLINT);
INSERTINTO"person"VALUES(1,'john',30);
INSERTINTO"person"VALUES(2,'david',35);
INSERTINTO"person"VALUES(3,'henry',40);
DELETEFROM sqlite_sequence;
INSERTINTO"sqlite_sequence"VALUES('person',3);
COMMIT;
sqlite>
sqlite> .output stdout
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), age SMALLINT);
INSERT INTO "person" VALUES(1,'john',30);
INSERT INTO "person" VALUES(2,'david',35);
INSERT INTO "person" VALUES(3,'henry',40);
DELETE FROM sqlite_sequence;
INSERT INTO "sqlite_sequence" VALUES('person',3);
COMMIT;
sqlite>
以上三个方法的第一个参数都是表示要操作的表名;insert中的第二个参数表示如果插入的数据每一列都为空的话,需要指定此行中某一列的名称,系统将此列设置为NULL,不至于出现错误;insert中的第三个参数是ContentValues类型的变量,是键值对组成的Map,key代表列名,value代表该列要插入的值;update的第二个参数也很类似,只不过它是更新该字段key为最新的value值,第三个参数whereClause表示WHERE表达式,比如“age > ? and age < ?”等,最后的whereArgs参数是占位符的实际参数值;delete方法的参数也是一样。
publicvoid onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ALTER TABLE person ADD COLUMN other STRING");
}
}
package com.scott.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "test.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context) {
//CursorFactory设置为null,使用默认值
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//数据库第一次被创建时onCreate会被调用
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS person" +
"(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)");
}
//如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ALTER TABLE person ADD COLUMN other STRING");
}
}
public Person(String name, int age, String info) {
this.name = name;
this.age = age;
this.info = info;
}
}
package com.scott.db;
public class Person {
public int _id;
public String name;
public int age;
public String info;
public Person() {
}
public Person(String name, int age, String info) {
this.name = name;
this.age = age;
this.info = info;
}
}
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
// 如果mDatabase不为空已打开并且不是只读模式 则返回该实例
return mDatabase;
}
if (mIsInitializing) {
thrownew 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;
// 如果mDatabase不为空则加锁 阻止其他的操作
if (mDatabase != null)
mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
// 打开或创建数据库
db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}
// 获取数据库版本(如果刚创建的数据库,版本为0)
int version = db.getVersion();
// 比较版本(我们代码中的版本mNewVersion为1)
if (version != mNewVersion) {
db.beginTransaction();// 开始事务
try {
if (version == 0) {
// 执行我们的onCreate方法
onCreate(db);
} else {
// 如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法
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) {
// 如果mDatabase有值则先关闭
try {
mDatabase.close();
} catch (Exception e) {
}
mDatabase.unlock();// 解锁
}
mDatabase = db;// 赋值给mDatabase
} else {
// 打开失败的情况:解锁、关闭
if (mDatabase != null)
mDatabase.unlock();
if (db != null)
db.close();
}
}
}
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
// 如果mDatabase不为空已打开并且不是只读模式 则返回该实例
return mDatabase;
}
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;
// 如果mDatabase不为空则加锁 阻止其他的操作
if (mDatabase != null)
mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
// 打开或创建数据库
db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}
// 获取数据库版本(如果刚创建的数据库,版本为0)
int version = db.getVersion();
// 比较版本(我们代码中的版本mNewVersion为1)
if (version != mNewVersion) {
db.beginTransaction();// 开始事务
try {
if (version == 0) {
// 执行我们的onCreate方法
onCreate(db);
} else {
// 如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法
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) {
// 如果mDatabase有值则先关闭
try {
mDatabase.close();
} catch (Exception e) {
}
mDatabase.unlock();// 解锁
}
mDatabase = db;// 赋值给mDatabase
} else {
// 打开失败的情况:解锁、关闭
if (mDatabase != null)
mDatabase.unlock();
if (db != null)
db.close();
}
}
}
/**
* This method allows the activity to take care of managing the given
* {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
* That is, when the activity is stopped it will automatically call
* {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
* it will call {@link Cursor#requery} for you. When the activity is
* destroyed, all managed Cursors will be closed automatically.
*
* @param c The Cursor to be managed.
*
* @see #managedQuery(android.net.Uri , String[], String, String[], String)
* @see #stopManagingCursor
*/
Cursor结果集需要注意些什么:一个最需要注意的是,在我们的结果集中必须要包含一个“_id”的列,否则SimpleCursorAdapter就会翻脸不认人,为什么一定要这样呢?因为这源于SQLite的规范,主键以“_id”为标准。解决办法有三:第一,建表时根据规范去做;第二,查询时用别名,例如:SELECT id AS _id FROM person;第三,在CursorWrapper里做文章: