对于重复或者是结构化的数据把他们保存在数据库当中是十分理想的,如通讯录的联系人等。
实现一个合同类
创建Sqlite数据库的第一步就是实现一个合同类 ,所谓合同类就是我们将数据库的表名,以及列的名字都放在一个类文件当中。假如说们创建一个student表,其中有学号以及姓名这两列。代码如下
//类的名字最好定义成什么什么Contract,Contract是合同的意思
public class FeedReaderContract {
public static abstract class FeedEntry {
public static final String DBNAME="grade.db";//数据库的名字
public static final String TABLE_NAME="student";
public static final String COLUMN_NAME_NUMBER="id";
public static final String COLUMN_NANE_STUDENT_NAME="name";
}
}
继承SQLiteOpenHelper
再创建好合同类之后,我们需要自己继承SQLiteOpenHelper,这里我们需要注意几个方法。第一个就是构造函数,第二是onCreate方法(如果你对四大组件很熟悉,那么你应该很眼熟。),还有一个onUpgrade()方法,这个方法是负责来升级数据库的版本。下面我们先来一段源码。
/*
* @param context to use to open or create the database
* @param name of the database file, or null for an in-memory database
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
*/
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
this(context, name, factory, version, new DefaultDatabaseErrorHandler());
}
这就是我们平常所使用的构造函数的源码,如果你自己看过他的源码,就会发现他有两个构造函数,有没有注意到构造函数里的this?其实就是调用那个构造函数。这里我们只分析这个。
- context 也是就是创建和使用数据库的这个context
- name 数据库的名字
- factory 用来创建cusor的CursorFactory
version 数据库的版本号
继承SqliteOpenHelper代码如下,我们需要注意就是前面创建表那代码,该有空格的地方应该要有空格,按照平常我们写sql语句那样写。
public class StudentOpenHelper extends SQLiteOpenHelper {
private static final String SQL_CREATE_ENTRIES=
"CREATE TABLE "+FeedEntry.TABLE_NAME+" ("+FeedEntry.COLUMN_NAME_NUMBER+" INTEGER PRIMARY KEY,"
+FeedEntry.COLUMN_NANE_STUDENT_NAME+" TEXT)";
public StudentOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
获得SQLiteDatabase对象
两种方法获得
- getWritableDatabase()
- getReadableDatabase()
下面的注释是getWritableDatabase()的注释,我简单解释下,看看它告诉了我们什么。
/**
* Create and/or open a database that will be used for reading and writing.
* The first time this is called, the database will be opened and
* {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be
* called.
*
* <p>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 the database.)
* Errors such as bad permissions or a full disk may cause this method
* to fail, but future attempts may succeed if the problem is fixed.</p>
*
* <p class="caution">Database upgrade may take a long time, you
* should not call this method from the application main thread, including
* from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
*
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
从上面我们可以得出一下结论:
- 不能在主线程中调用
- 一旦成功打开就会缓存,所以close()这个方法使用的要谨慎
- 调用不成功会抛出SQliteException这个异常
两种方法都会返回可读和可写的数据库实例
增加
SQLiteDatabase db = mDbHelper.getWritableDatabase();
获得SQLiteDatabase对象
还有一个重要的对象叫ContentValues,这个对象提供了一个键值对的存储,只不过键的类型是String类型,而值得类型可以有很多种。具体可以看相关文档,如果我们想向表中插入一个行,只需要调用SQLiteDatabase的insert()方法,源码如下,我来一一解释参数是干什么的
public long insert(String table, String nullColumnHack, ContentValues values) {
第一个是表的名字,第二个被称为空行入侵,假设我们要添加一个空行,那么必须显式的提供一个列名,当然后面的contentvalue也要为空,如果我们插入不是一个空行,那么只需要把它设置为NULL就行了。第三个也就是我前面介绍的ContentValues对象。
这里还有一个方法就是insertOrThrow,区别就是第一个方法调用失败会返回-1,而第二个方法则会抛出异常。
查询
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy)
简单介绍这几个参数的意思,第一个就是所查的表的名字,第二个是返回的列的名字,如果为空,则返回所有的列名。第三个就是where,定义返回的行,如果为空,则返回所有的行,第四个参数,则是代替where句子里的?,这个是通配符。第五个参数就是SQL里面的group by,第六个参数就是SQL里面的 SQL HAVING,第七个就是SQL里面的SQL ORDER BY。查询成功则会返回一个Cusor对象,具体Cusor怎么用你可以查看相关文档,这里我只说重点,用完以后一定要 记得关闭(close方法),否则会占用资源,这是一个十分严重的问题
删除
public int delete(String table, String whereClause, String[] whereArgs) {
SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
(!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
第一个参数为表的名字,第二个参数where里的东西,第三个则是相应的参数,和上面的相同。返回值如果为1是删除了所有的行,为0则是没有行数受到影响,或者是返回影响的行数。注意看上面的源码。
更新
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
}
第一个参数为表的名字,第二个为ContentValues对象,第三个和第四个都和上面的相同,这里就不解释了。
有问题,欢迎留言提问,或者发送邮箱