android開發第五天sqlite資料庫操作

來源:互聯網
上載者:User

 

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.