Android SQLite數據庫的使用

前言

Android的SQLite對本地數據的保存起到重要的作用,也可以用來做一些網絡數據的緩存。

使用SQLiteOpenHelper

使用 SQLiteOpenHelper可以很方便的創建和打開一個數據庫;

  • 繼承SQLiteOpenHelper;
public class ItemsDBHelper extends SQLiteOpenHelper 
  • 在類的前面寫上數據庫名、表名、列名及數據庫創建語句;寫上類的私有屬性;
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Items.db";

    public static final String TABLE_NAME = "items";
    public static final String COLUMN_SMS = "sms";
    public static final String COLUMN_NUMBER = "number";

    public static final String CREATE_TABLE ="create table " + TABLE_NAME + " ("
            + "id integer primary key autoincrement,"
            + COLUMN_SMS +" text, "
            + COLUMN_NUMBER + " text)";

    private Context mContext;
    private SQLiteDatabase mDB;
  • 覆寫構造方法;傳入上下文context;調用super,傳入參數;使用getWritableDatabase獲取數據庫對象;
    public ItemsDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mContext = context;
        mDB = this.getWritableDatabase();
    }
  • 覆寫抽象方法;在onCreate中執行創建數據庫的任務;
    @Override
    public void onCreate(SQLiteDatabase db) {
        mDB.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

保存數據

  • 先判斷下數據的存在,如果存在,就不繼續插入數據,從方法中返回;使用ContentValues類,作爲數據插入的對象;
    public void saveItem(ItemBean itemBean) {
        if(hasItem(itemBean)) {
            return;
        }
        ContentValues values = new ContentValues();
        values.put(COLUMN_SMS, itemBean.getSms());
        values.put(COLUMN_NUMBER, itemBean.getNumber());
        mDB.insert(TABLE_NAME, "", values);
    }

刪除數據

  • 使用SQLiteDatabasedelete方法;table表名,whereClause條件,whereArgs條件參數;
public int delete(String table, String whereClause, String[] whereArgs)
  • 代碼如下:
    public void deleteItem(ItemBean itemBean) {
        String selection = COLUMN_SMS + "=? AND " + COLUMN_NUMBER + "=?";
        String[] selectionArgs = {itemBean.getSms(), itemBean.getNumber()};
        mDB.delete(TABLE_NAME, selection, selectionArgs);
    }

查詢數據

  • 使用SQLiteDatabasequeryquery 方法;table表名,columns要返回的列,selection條件,selectionArgs條件參數,groupBy分組,having包含,orderBy排序;返回一個Cursor對象,來封裝查詢好的數據;
public Cursor query(String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having, String orderBy)
  • 取出所有數據;
    public ArrayList<ItemBean> loadItems() {
        ArrayList<ItemBean> itemBeans = new ArrayList<ItemBean>();
        Cursor cursor = mDB.query(TABLE_NAME, null, null, null, null, null,null);
        if(cursor != null) {
            while (cursor.moveToNext()) {
                ItemBean itemBean = new ItemBean();
                itemBean.setSms(cursor.getString(cursor.getColumnIndex(COLUMN_SMS)));
                itemBean.setNumber(cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER)));
                itemBeans.add(itemBean);
            }
        }
        Log.i(Config.TAG, "ItemsDBHelper->loadItems: " + itemBeans);
        return itemBeans;
    }
  • 按查詢條件取出數據;
    public ArrayList<String> getNumbers(String sms) {
        ArrayList<String> sNumbers = new ArrayList<String>();

        String selection = COLUMN_SMS + "=?";
        String[] selectionArgs = new String[] {sms};
        Cursor cursor = mDB.query(TABLE_NAME, null, selection, selectionArgs, null, null,null);
        if(cursor != null) {
            while (cursor.moveToNext()) {
                String sNumber = cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER));
                sNumbers.add(sNumber);
            }
        }
        return sNumbers;
    }
  • 判斷數據的存在;
    public boolean hasItem(ItemBean itemBean) {
        String selection = COLUMN_SMS + "=? AND " + COLUMN_NUMBER + "=?";
        String[] selectionArgs = new String[] {itemBean.getSms(), itemBean.getNumber()};
        Cursor cursor = mDB.query(TABLE_NAME, null, selection, selectionArgs, null, null,null);
        if(cursor == null || cursor.getCount() == 0) {
            return false;
        } else {
            return true;
        }
    }

修改數據

  • 先刪除,再添加;這種方式屬於偷懶的方式,親測有效,但不知道有沒有什麼副作用,慎用;
    public void updateItem(ItemBean oldItemBean, ItemBean newItemBean) {
        deleteItem(oldItemBean);
        saveItem(newItemBean);
    }
  • 正確方法;
    public void updateItem(ItemBean oldItemBean, ItemBean newItemBean) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_NUMBER, newItemBean.getNumber());
        values.put(COLUMN_SMS, newItemBean.getSms());

        String selection = COLUMN_SMS + "=? AND " + COLUMN_NUMBER + "=?";
        String[] selectionArgs = {oldItemBean.getSms(), oldItemBean.getNumber()};

        mDB.update(TABLE_NAME, values, selection, selectionArgs);
    }

總結

  • 使用SQLiteOpenHelper 方便管理SQLite數據庫;
  • 數據庫的增、刪、改、查;
  • 增,要先判斷一下數據有沒有存在;使用ContentValues來封裝要插入的數據;
  • 查,最後得出Cursor對象,使用moveToNext 來獲取下一條數據;
  • 刪和改,與增和查相似;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章