}
Context 类的 openDatabase 可以打开一个已经存在的数据库,如果数据库不存在,将会
抛出
FileNotFoundException 异常。可以通过 Context 类的 createDatabase 函数建立一个新的
数据库。通过调用
SQLiteDatabase 的 execSQL 方法,执行一条 SQL 语句建立一个新的数据
表。
2.获取表中的数据
代码如下:
public List
﹤Row
﹥ fetchAllRows() {
ArrayList
﹤Row
﹥ ret = new ArrayList﹤Row﹥();
try {
Cursor c =
db.query(DATABASE_TABLE, new String[] {
"rowid", "title", "body"}, null, null, null, null, null);
int numRows = c.count();
c.first();
for (int i = 0; i
﹤ numRows; ++i) {
Row row = new Row();
row.rowId = c.getLong(0);
row.title = c.getString(1);
row.body = c.getString(2);
ret.add(row);
c.next();
}
} catch (SQLException e) {
Log.e("booga", e.toString());
}
return ret;
}
建立一个游标类
Cursor 通过 SQLiteDatabase 的 query 方法查询一个表格。有了 Cursor 就
可以遍历所有的记录了。
3 添加新的记录
public void createRow(String title, String body) {
ContentValues initialValues = new ContentValues();
initialValues.put("title", title);
initialValues.put("body", body);
db.insert(DATABASE_TABLE, null, initialValues);
}