【数据存储】使用ContentValues封装数据(3)

使用ContentValues修改MytabOperate类中的方法

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

public class MytabOperate {
    // 表示要操作的数据表名称
    private static final String TABLENAME = "mytab"; 
    // 数据库操作
    private SQLiteDatabase db = null; 
    // 构造方法
    public MytabOperate(SQLiteDatabase db) {
        this.db = db;
    }
    public void insert(String name,String birthday) {
        ContentValues cv = new ContentValues() ;
        cv.put("name", name) ;
        cv.put("birthday", birthday) ;
        this.db.insert(TABLENAME, null, cv) ;
        this.db.close() ;
    }
    public void update(int id, String name, String birthday) {
        ContentValues cv = new ContentValues() ;
        cv.put("name", name) ;
        cv.put("birthday", birthday) ;
        // 更新条件
        String whereClause = "id=?" ;
        // 更新ID
        String whereArgs[] = new String[]{String.valueOf(id)} ;
        this.db.update(TABLENAME, cv, whereClause, whereArgs) ;
        this.db.close() ;
    }
    public void delete(int id) {
        String whereClause = "id=?" ;
        String whereArgs[] = new String[]{String.valueOf(id)} ;
        this.db.delete(TABLENAME, whereClause, whereArgs) ;
        this.db.close() ;
    }
}

虽然通过SQLiteDatabase对象可以执行SQL语句的操作,但从实际开发来讲,使用ContentValues更为标准,这样最大好处是和ContentProvider关联,但是如果现在用户并不需要将数据库操作发布成ContentProvider,则还是使用SQL操作会更方便。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2013-06-09 16:34  大米稀饭  阅读(627)  评论(0编辑  收藏  举报