android-資料庫SQLite相關,android-sqlite

來源:互聯網
上載者:User

android-資料庫SQLite相關,android-sqlite

android平台下的SQLite資料庫是一種輕量級資料庫,支援標準的SQL語句。

本文將介紹

  • android資料庫的建立
  • 利用sql語句對資料庫增刪改查
  • 系統api資料庫增刪改查
  • 資料庫的事務
  • 1,資料庫的建立
     

    步驟:

  • 寫一個類繼承SQLiteOpenHelper
  • 在建構函式中指定 資料庫名稱,遊標工廠, 版本號碼
  • 初始化資料庫,執行getWritableDatabase或getReadableDatabase, 建立或開啟一個資料庫.
  • onCreate裡執行SQL建立語句

  •        android平台下資料庫的建立需要一個輔助類繼承SQLiteOpenHelper,並且需要重寫父類的構造方法。

  • /** * 資料庫建立輔助類 寫一個類繼承SQLiteOpenHelper * * @author wgk * */ public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {    public PersonSQLiteOpenHelper(Context context) {         super(context, "PERSON.db", null, 1);//此處是super,直接調用父類的構造方法     }    /**      *      * 構造方法,用於建立一個輔助類,用於開啟/建立/管理一個資料庫      *      * @param context      *            上下文      * @param name      *            資料庫檔案的名字      * @param factory      *            遊標工廠 Cursor 遊標(指標), 本身並不儲存資料. 儲存資料庫的引用.      * @param version      *            資料庫版本      */     public PersonSQLiteOpenHelper(Context context, String name,             CursorFactory factory, int version) {         super(context, name, factory, version);     }    @Override     // 資料庫第一次被建立時調用,適合初始化操作     public void onCreate(SQLiteDatabase db) {         // 建立表         db.execSQL("create table person ("                 + " _id integer primary key autoincrement, "                 + " name varchar(20), " + " age integer);");     }    @Override     // 資料庫更新時調用這個方法     // 用於執行表的更新操作     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {         // TODO Auto-generated method stub  }}

        這個類僅僅是一個輔助類,若想使用資料庫,還需要建立一個資料庫訪問類PersonDAO。

  • 2,對資料庫進行增刪改查

  • public class PersonDAO{    private final Context context;    private PersonSQLiteOpenHelper helper;    public PersonDAO(Context context) {        this.context = context;        helper = new PersonSQLiteOpenHelper(context);    }    /**     * @param name     * @param age     */    public void add(String name, int age) {        SQLiteDatabase db = helper.getWritableDatabase();        // db.execSQL("insert into person (name,age) values ('"+name+"',"+age+")");        // 防止SQL注入        db.execSQL("insert into person (name,values) values(?,?)",                new Object[] { name, age });    }    /**     * 根據名字刪除一條資料     *      * @param name     */    public void delete(String name) {        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("delete from person where name=?", new Object[] { name });    }//根據名字更新年齡
        public void update(int age, String name) {        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("update person set age=? where name=?", new Object[] { age,name });    }    public void querySingleRecord(String nameStr) {        SQLiteDatabase db = helper.getReadableDatabase();        Cursor cursor = db.rawQuery("select * from person where name=?",new String[] { nameStr });        if (cursor != null && cursor.moveToFirst()) {            String _id = cursor.getString(0);            String name = cursor.getString(1);            String age = cursor.getString(2);            System.out.println("_id: " + _id);            System.out.println("name: " + name);            System.out.println("age: " + age);            cursor.close();        }    }    /**     * 查詢所有資料     */    public void queryAll() {        SQLiteDatabase db = helper.getReadableDatabase();        Cursor cursor = db.rawQuery("select * form person", null);        if (cursor != null && cursor.getCount() > 0) {            while (cursor.moveToNext()) {                int _id = cursor.getInt(cursor.getColumnIndex("_id"));                String name = cursor.getString(cursor.getColumnIndex("name"));                int age = cursor.getInt(cursor.getColumnIndex("age"));                System.out.println("_id: " + _id);                System.out.println("name: " + name);                System.out.println("age: " + age);                System.out.println("-----------------");            }            cursor.close();        }    }}
  • 注意:在獲得資料庫輔助類對象時,此時並未建立資料庫,只有在輔助類對象調用getxxxxDatabase方法(建立可讀或者可寫的資料庫)時,才建立資料庫。

  • //此時並未建立資料可PersonSQLiteOpenHelper helper = new PersonSQLiteOpenHelper(getContext());// 擷取一個可讀/可寫的資料庫, 真正建立了資料庫helper.getWritableDatabase();
     
    3,使用goole的api操作資料庫
  • 除了使用SQL語句來進行增刪改查,還可以使用google提供的api。

    //主要語句
       // 增      db.insert("person", "name", values);   // 刪    db.delete("person", "name=?", new String[]{name});   // 改    db.update("person", values, "name=?", new String[]{name});    //查    Cursor cursor = db.query("person",  // 表名            null,  // 要查詢列名 new String[]{name,age}            "name = ?",  // 查詢條件            new String[]{nameStr},// 條件參數            null,   // 分組             null,   // 分組            null);   // 排序

    使用google的api對PersonDAO進行修改,如下

    /** * 使用google提供的api來操作資料庫 *  * 資料庫訪問對象 * @author wgk * */public class PersonDAO3 {        private final Context context;    private PersonSQLiteOpenHelper helper;    public PersonDAO3(Context context){        this.context=context;        helper=new PersonSQLiteOpenHelper(context);    }    /**     * 增加一條資料     * @param name     * @param age     */    public void add(String name,int age){        SQLiteDatabase db=helper.getWritableDatabase();        ContentValues values=new ContentValues();        values.put("name", name);        values.put("age", age);                //若需要插入一條空的資料,需要指定任意一個列的名稱,以避免異常        String nullColumnHack="null";        long insert=db.insert("person", nullColumnHack, values);        System.out.println(insert);    }    /**     * 刪除一條資料根據名字     * @param name     */    public void delete(String name){        SQLiteDatabase db=helper.getWritableDatabase();        int delete=db.delete("person", "name=?", new String[]{name});        System.out.println(delete);                }    /**     * 更新年齡!根據名字     * @param age     * @param name     */    public void update(int age,String name){        SQLiteDatabase db=helper.getWritableDatabase();        ContentValues values=new ContentValues();        values.put("age", age);        int update =db.update("person", values, "name=?", new String[]{name});        System.out.println(update);    }        /**     * 查!根據一個人的名字     * @param name     */    public void querySingleRecord(String nameStr){        SQLiteDatabase db=helper.getReadableDatabase();        Cursor cursor=db.query("person",                null,//列名                "name=?",//查詢條件                new String[]{nameStr},//查詢參數                null, //分組                null,//分組                null);//排序        if(cursor!=null&&cursor.moveToFirst()){            String _id=cursor.getString(0);            String name=cursor.getString(1);            String age=cursor.getString(2);            System.out.println("_id: " + _id);            System.out.println("name: " + name);            System.out.println("age: " + age);                        //關閉cursor            //關閉cursor            //關閉cursor            cursor.close();        }            }    /**     * 查詢所有資料     */    public void queryAll(){        SQLiteDatabase db=helper.getReadableDatabase();        Cursor cursor=db.query("person",                null,                null,                null,                 null,                 null,                 "_id DESC");//排序        if(cursor!=null&&cursor.getCount()>0){            while(cursor.moveToNext()){                int _id=cursor.getInt(cursor.getColumnIndex("_id"));                String name=cursor.getString(cursor.getColumnIndex("name"));                int age=cursor.getInt(cursor.getColumnIndex("age"));                                System.out.println("_id: " + _id);                System.out.println("name: " + name);                System.out.println("age: " + age);                           
                  }            //關閉cursor            //關閉cursor            //關閉cursor            cursor.close();        }    }        }
    兩種方式的比較

    1.利用SQL語句進行增刪改查
    優點:靈活, 根據需要進行表的級聯查詢.

    缺點:容易出錯. 沒有傳回值

    2.利用系統API增刪改查

    優點:不容易出錯. 有傳回值

    缺點:不靈活, 效率稍低, 拼接sql語句耗時

    -------------------------------------------------我是分割線-------------------------------------------------資料庫的事務(Transaction)

    以laowang給xiaosan轉賬1000的例子寫一段demo如下

    public class TransactionDemo extends AndroidTestCase{        public void transactionDemo(){                PersonSQLiteOpenHelper helper= new PersonSQLiteOpenHelper(getContext());        //此時才真正建立資料庫         SQLiteDatabase db=helper.getWritableDatabase();        try{              //開始事務               db.beginTransaction();                          //轉出1000             db.execSQL("update person set money=money-1000 where name=?", new Object[]{"laowang"});                        //在執行至復原點之前,並不會對資料庫進行真的操作,一切都在記憶體中進行,只有執行到復原點之後,才會影響到資料庫            //int i =1/0;            //轉入1000            db.execSQL("update person set money=money+1000 where name=?", new Object[]{"xiaosan"});            //設定復原點              db.setTransactionSuccessful();        }catch (Exception e){            e.printStackTrace();        }finally{            db.endTransaction();                    }    }

     

    總結:

    最近都是在下班之後才有時間寫寫blog。現在只是把以前的筆記稍加整理,可能有些知識點說得不精確,有些策略沒有做到最優,這是由於當時學習時沒有認識到。我並沒有刻意揀出來,懇請大家一起指正。

    我要去玩夢幻了,hiahiahiahiahia~~~

    -------------------------------------------------基礎要像磐石!!!

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.