标签:
上篇博客提到过SQLite,它是嵌入式数据库,由于其轻巧但功能强大,被广泛的用于嵌入式设备当中。后来在智能手机、平板流行之后,它作为文件型数据库,几乎成为了智能设备单机数据库的必选,可以随着安卓app打包到apk文件当中。
SQLite的官方网站是http://www.sqlite.org/,可以任意下载,上面也有详尽的文档可以参考,这篇博客重点关注SQLite在Android开发中如何使用。
在Android开发中,推荐建立一个类继承自SQLiteOpenHelper来创建数据库操作类,比如:
- public class DBHelper extends SQLiteOpenHelper {
-
- private static final String database = "test.db";
- private static final Integer version = 1;
-
- public DBHelper(Context context) {
-
-
- super(context, database, null, version);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
-
- String sql = "create table Score(id integer primary key autoincrement,name varchar(20),point integer)";
- db.execSQL(sql);
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
-
-
- }
- }
上面的代码有3点需要注意:
1、构造函数(方法)中指定了数据库的名称和版本号
它会默认的在data/data/包名/databases/目录下创建这个数据库,当然你也可以指定数据库文件存在的路径;版本号设置为1,如果你要想升级,可以在构造方法的参数中加上version,以便初始化。
2、onCreate是在数据库文件没有创建的时候执行,如果有了的话则不执行
3、onUpgrade是在新的指定版本号高于旧的指定版本号的时候执行,一般在数据库升级的时候需要操作
然后我们建一个具体的数据库操作类:
- public class ScoreOp {
-
-
- public long insert(SQLiteDatabase db, String name, Integer point) {
- try {
- db.beginTransaction();
- ContentValues values = new ContentValues();
- values.put("name", name);
- values.put("point", point);
- long result = db.insert("Score", null, values);
- if (result != -1) {
- db.setTransactionSuccessful();
- }
- return result;
- } finally {
- db.endTransaction();
- }
- }
-
-
- public int update(SQLiteDatabase db, String name, Integer point) {
- try {
- db.beginTransaction();
- ContentValues values = new ContentValues();
- values.put("name", name);
- values.put("point", point);
- int result = db.update("Score", values, "name = ?",
- new String[] { name });
- db.setTransactionSuccessful();
- return result;
- } finally {
- db.endTransaction();
- }
- }
-
-
- public long delete(SQLiteDatabase db, String name) {
- try {
- db.beginTransaction();
- int result = db.delete("Score", "name = ?", new String[] { name });
- db.setTransactionSuccessful();
- return result;
- } finally {
- db.endTransaction();
- }
- }
-
-
- public Cursor query(SQLiteDatabase db, Integer point) {
- return db.query("Score",
- new String[] { "name", "sum(point) as points" }, null, null,
- "name", "sum(point)>=" + point, "name asc", "0,10");
- }
-
-
- public Cursor query(SQLiteDatabase db, String sql, String[] selectionArgs) {
- return db.rawQuery(sql, selectionArgs);
- }
- }
这上面封装了CRUD操作,而且都是带事务的(执行多条SQL时需要),值得关注的是最后的两个query方法。
第一个query是指定了一个复杂sql查询语句的情况。
按照顺序,参数的含义如下:
1)、table The table name to compile the query against.
指定的查询的表名
2)、columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn‘t going to be used.
返回的查询列表的列名
3)、selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
where条件,不包括where关键字
4)、selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
where条件指定的参数值
5)、groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
group by分组后面跟着的列名
6)、having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
having 后面紧跟着的在分组基础上进一步筛选的内容
7)、orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
order by后面根据某字段排序
8)、limit Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
limit关键字,分页查询时使用
实际上上面对应的这8个参数,就是对应如下SQL查询语句各关键字后面的内容,其原理就是通过指定参数拼接如下SQL语句。
这里顺便提一下,SQLite Expert是非常好用的管理SQLite数据库的工具,可以在http://www.sqliteexpert.com/下载到,也可以直接搜索下载相应破解版本。
回到第二个query方法,参数很简单,只有一个sql语句以及一个string数组(提供sql语句参数的值)。这个方法的意义就在于它很灵活,可以直接把能够执行的sql扔进去执行,而且是参数化的,是第一种查询方法很有力的补充。
好,最后我们就可以写测试代码来验证了。界面很简单,直接放置一个按钮即可。
- public class SQLiteActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_sqlite);
-
- Button btn = (Button) findViewById(R.id.btn);
- btn.setOnClickListener(new View.OnClickListener() {
-
- @Override
- public void onClick(View v) {
- DBHelper dbHelper = new DBHelper(SQLiteActivity.this);
-
-
- SQLiteDatabase wdb = dbHelper.getWritableDatabase();
-
-
- ScoreOp scoreOp = new ScoreOp();
- scoreOp.insert(wdb, "zhang3", 98);
- scoreOp.insert(wdb, "zhang3", 94);
-
- scoreOp.insert(wdb, "li4", 92);
- scoreOp.insert(wdb, "wang5", 89);
- scoreOp.insert(wdb, "wang5", 82);
-
-
- scoreOp.update(wdb, "li4", 90);
-
-
- scoreOp.delete(wdb, "li4");
-
-
- SQLiteDatabase rdb = dbHelper.getReadableDatabase();
-
-
-
-
-
- Cursor cursor = scoreOp
- .query(rdb,
- "select name,sum(point) as points from Score group by name having sum(point)>=192 order by name asc limit ?,?",
- new String[] { "0", "10" });
- while (cursor.moveToNext()) {
- String name = cursor.getString(cursor
- .getColumnIndex("name"));
- Integer points = cursor.getInt(cursor
- .getColumnIndex("points"));
-
- Toast.makeText(SQLiteActivity.this,
- "姓名:" + name + ";总分:" + points, Toast.LENGTH_SHORT)
- .show();
- }
- cursor.close();
- }
- });
-
- }
-
- }
点击按钮执行之后就可以弹出符合条件的数据。如果不放心,可以切换到DDMS界面,选择File Explorer选项卡,找到路径下的我们创建的test.db文件,Pull(拉取)到电脑磁盘上,用SQLite Expert等工具打开验证。
Android开发系列之SQLite
标签:
原文地址:http://www.cnblogs.com/guwei4037/p/5582942.html