Android学习之使用SQLite实现简单的(CRUD)增删改查

来源:互联网 发布:淘宝免费买东西的软件 编辑:程序博客网 时间:2024/06/05 19:01

使用SQlite实现简单的CRUD

首先需要一个帮助类继承SQLiteOpenHelper这个抽象类,如下:

public class DbHelper extends SQLiteOpenHelper {    private static final int VERSION = 1;    private static final String DB_NAME = "test.db";    public static final String TABLE_NAME = "TEST";    public static final String COLUMN_NAME_CONTENT = "content";    private static final String CREATE_TABLE_SQL =            "create table " + TABLE_NAME + "(id integer primary key autoincrement," +  COLUMN_NAME_CONTENT + " varchar)";    public DbHelper(Context context) {        /**         * 第一个参数:当前activity实例         * 第二个参数:数据库名称         * 第三个参数:用来创建游标对象         * 第四个参数:数据库版本号         */        super(context, DB_NAME, null, VERSION);    }    @Override    public void onCreate(SQLiteDatabase db) {        // 数据库被创建后调用此方法        // 该方法内用来初始化和创建表        db.execSQL(CREATE_TABLE_SQL);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        // 该方法用来更新数据库,可在此处更改表结构或删除表         db.execSQL("drop table if exists TEST");         onCreate(db);    }}

Note:因为对数据库的操作可能是耗时的,所以最好将对数据库的操作写在后台线程里(可以使用AsynTask,AsynTask的使用推荐此文:http://blog.csdn.net/liuhe688/article/details/6532519)

以下为了代码简洁,只贴出实现代码

增加

@Overrideprotected Long doInBackground(String... params) {    long rowId = 0;    // 取得数据库写操作    SQLiteDatabase db = mDbHelper.getWritableDatabase();    // 创建ContentValues对象并设置键值对    ContentValues cValues = new ContentValues();    cValues.put(DbHelper.COLUMN_NAME_CONTENT, params[0]);    // 开始事务    db.beginTransaction();    try {        // 方式一:插入语句,返回新行的rowId        /**         * 第一个参数:表名         * 第二个参数:设为null则不插入NULL行,否则会插入NULL行         * 第三个参数:上面设置的键值对         */        rowId = db.insert(DbHelper.TABLE_NAME, null, cValues);        // 方式二:注意''号和空格        /*String sql = "insert into " + DbHelper.TABLE_NAME + " values(null,\'" + params[0] + "\')";        Log.d(TAG, "sql:" + sql);        db.execSQL(sql);*/        // 提交事务,默认为false,会rollback        db.setTransactionSuccessful();    } finally {         // 结束事务,如果不及时结束事务,数据库管理系统会在超时后帮你结束事务,但会影响并发性能        db.endTransaction();            }    return rowId;}

推荐使用方式一,若使用方式二极容易出错,我就栽跟头过( ▼-▼ )。

删除

@Overrideprotected Long doInBackground(String... params) {     SQLiteDatabase db = mDbHelper.getWritableDatabase();    db.beginTransaction();    try {        long rowId = db.delete(                DbHelper.TABLE_NAME,    // 表名                "id=?",                 // where条件语句,根据id删除                new String[]{params[1]} // where条件参数值                );         db.setTransactionSuccessful();    } finally {        db.endTransaction();            }    return rowId;}

更新

@Overrideprotected Long doInBackground(String... params) {    // 取得数据库写操作    SQLiteDatabase db = mDbHelper.getWritableDatabase();    // 创建ContentValues对象并设置键值对    ContentValues cValues = new ContentValues();    cValues.put(DbHelper.COLUMN_NAME_CONTENT, params[2]);    db.beginTransaction();    try {        long rowId = db.update(                    DbHelper.TABLE_NAME,    // 表名                    cValues,                // 要更新的值                    "id=?",                 // where条件语句,根据id                    new String[]{params[1]} // where条件参数值            );        db.setTransactionSuccessful();    } finally {        db.endTransaction();            }    return rowId;}

查询

@Overrideprotected String doInBackground(String... params) {    SQLiteDatabase db = mDbHelper.getReadableDatabase();    Cursor cursor = db.query(                DbHelper.TABLE_NAME,            // 表名                new String[]{"id", "content"},  // 要查询的列                "id=?",                         // where子句,根据id来查询                new String[]{params[0].toString()},// where子句条件的值                null,                              // group分组                null,                              // having条件                "id DESC"                          // 根据id降序        );    String id = null, content = null;    // 移动游标到结果集的首行,如果为真则依次取出游标所指的列索引所对应的值    if (cursor.moveToFirst()) {        for (int i = 0; i < cursor.getCount(); i++) {            cursor.move(i);            id = cursor.getString(cursor.getColumnIndex("id"));            content = cursor.getString(cursor.getColumnIndex("content"));        }    }    cursor.close(); // 关闭游标,释放它的所有资源并使它无效    return content;}

要查询在cursor中的行,使用cursor的其中一个move方法,但必须在读取值之前调用。一般来说应该先调用moveToFirst()函数,将读取位置置于结果集最开始的位置。

对每一行,我们可以使用cursor的其中一个get方法如getString()或getLong()获取列的值。对于每一个get方法必须传递想要获取的列的索引位置(index position),索引位置可以通过调用getColumnIndex()或getColumnIndexOrThrow()获得。

写在最后

代码有些粗糙,不过都有注释。

如有问题请评论指出!

0 0