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

你可能感兴趣的:(Android开发)