android开发第五天sqlite数据库操作

 

复制代码
复制代码
public class DBHelper extends SQLiteOpenHelper {
    /**
     * 数据库名称
     */
    private static final String DB_NAME="mydb.db";
    /**
     * 数据库版本
     */
    private static final int DB_VERSION=1;
    public DBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }
    public DBHelper(Context context) {
        this(context,DB_NAME,null,DB_VERSION);
    }
    /**
     * 创建数据库
     */
    public void onCreate(SQLiteDatabase db) {
        String sql="create table customers(id integer primary key autoincrement,name varchar(20),age int)" ;
        db.execSQL(sql);
    }

    /**
     * 用于升级
     */
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        
    }

}
复制代码
复制代码

crud操作

复制代码
复制代码
public class CRUD {
    DBHelper helper;

    public CRUD(Context ctx) {
        helper = new DBHelper(ctx);
    }

    /**
     * insert操作
     */
    public void insert(String name, int age) {
        String sql = "insert into customers(name,age) values(?,?)";
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL(sql, new Object[] { name, age });
    }
    /**
     * update操作
     */
    public void update(String name, int age,int id){
        String sql = "update customers set name = ? , age = ? where id = ?" ;
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL(sql, new Object[]{name,age,id});
    }
    
    /**
     * delete操作
     */
    public void delete(int id){
        String sql = "delete from customers where id = ?" ;
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL(sql, new Object[]{id});
    }
    /**
     * 查询所有客户信息
     */
    public List<Object[]> findAll(){
        List<Object[]> list = new ArrayList<Object[]>();
        Object[] o = null ;
        String sql = "select * from customers" ;
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cur = db.rawQuery(sql, null);
        while(cur.moveToNext()){
            o = new Object[3];
            o[0] = cur.getInt(cur.getColumnIndex("id"));
            o[1] = cur.getString(cur.getColumnIndex("name"));
            o[2] = cur.getInt(cur.getColumnIndex("age"));
            list.add(o);
        }
        cur.close();
        return list ;
    }
}
复制代码
复制代码

移动开发QQ群:59516399

csdn下载链接:http://download.csdn.net/detail/wenwei19861106/4970365

posted on   南瓜饼  阅读(358)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2013年1月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9
点击右上角即可分享
微信分享提示