第五章 以資料為中心—資料存取(5),第五章存取

來源:互聯網
上載者:User

第五章 以資料為中心—資料存取(5),第五章存取
5.2.3 添加、刪除和修改操作

下面具體說明如何進行添加、刪除、修改的操作。下面我們將這些動作封裝在一個類DBHelper中,通過這個類的幾個方法,可以具體看到如何進行資料庫的各種操作。

// import略

public class DBHelper {

 

    private static final String[] COLS = new String[] { "_id","name"};

    private SQLiteDatabase db;

    private final DBOpenHelper dbOpenHelper;

 

    public DBHelper(final Context context) {

        this.dbOpenHelper = new DBOpenHelper(context);

        establishDb();

    }

    /**

     * 得到一個可寫的SQLite 資料庫,如果這個資料庫還沒有建立,

     * 那麼DBOpenHelper輔助類負責建立這個資料庫。

     * 如果資料庫已經建立,那麼直接返回一個可寫的資料庫。

     */

    private void establishDb() {

        if (this.db == null) {

             this.db = this.dbOpenHelper.getWritableDatabase();

        }

    }

    /**

     * 關閉資料庫

     */

           public void cleanup() {

        if (this.db != null) {

             this.db.close();

             this.db = null;

        }

    }

    /**

     * 插入一條資料

     */

    public void insert(String id,String name) {

        ContentValues values = new ContentValues();

        values.put("_id", id);

        values.put("name", id);

        this.db.insert(DBOpenHelper.TABLE_NAME, null, values);    

        cleanup();

    }

    /**

     * 更新一條資料

     */

    public void update(String id,String name) {

        ContentValues values = new ContentValues();

        values.put("_id", id);

        values.put("name", id);

        this.db.update(DBOpenHelper.TABLE_NAME, values, "_id=" + id,null);

        cleanup();

    }

    /**

     * 刪除一條資料

     */

    public void delete(final long id) {

        this.db.delete(DBOpenHelper.TABLE_NAME, "_id=" + id, null);

    }

    /**

     * 刪除所有資料

     */

    public void deleteAll() {

        this.db.delete(DBOpenHelper.TABLE_NAME, null, null);

    }

    private void query() {

        // 得到一個可寫的資料庫。

        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

        // 進行資料庫查詢

        Cursor cur = db.query(DBOpenHelper.TABLE_NAME, COLS, null, null, null, null, null);

        if(cur != null) {

            for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()) {

                int idColumn = cur.getColumnIndex(COLS[0]);

                int nameColumn = cur.getColumnIndex(COLS[1]);

                String id = cur.getString(idColumn);

                String name = cur.getString(nameColumn);

            }

cur.close();

        }

    }

}

 --------------------------------------------程式員賺錢不易 一定要學會理財平安陸金所 隸屬於平安集團的p2p平台年投資報酬率7%-9% 是替代銀行理財的首選個人經驗 推薦投資安鑫或者有擔保的彩虹項目不要投資安e 那個幾乎無法轉讓 想提前提現非常困難網站連結 http://affiliate.lufax.com/action/36XBU首次投資1000元即可額外賺幾百元 不賺白不賺--------------------------------------------

關於代碼“Cursor cur = db.query(DBOpenHelper.TABLE_NAME, COLS, null, null,null, null, null);”是將查詢到的資料放到一個Cursor當中。這個Cursor 裡邊封裝了這個資料表TABLE_NAME 當中的所有條列。query()方法相當的有用,在這裡我們簡單的講一下query中的參數。

第一個參數是資料庫裡邊表的名字,比如在我們這個例子,表的名字就是TABLE_NAME,也就是" myTableName "。

第二個參數是我們想要返回資料包含的列的資訊。在這個例子當中我們想要得到的列有id、name。我們把這兩個列的名字放到字串數組裡邊來。

第三個參數為selection,相當於sql語句的where部分,如果想返回所有的資料,那麼就直接置為null。

第四個參數為selectionArgs,在selection部分,你有可能用到”?”,那麼在selectionArgs定義的字串會代替selection中的”?”。

第五個參數為groupBy,定義查詢出來的資料是否分組,如果為null則說明不用分組。

第六個參數為having,相當於sql 語句當中的having部分。

第七個參數為orderBy,來描述我們期望的傳回值是否需要排序,如果設定為null則說明不需要排序。

Integernum = cur.getCount();通過getCount()方法,可以得到cursor 當中資料的個數。

下面我們來介紹Cursor類的一些常用方法。

5.2.4遊標的操作—使用Cursor

在資料庫中,遊標是一個十分重要的概念。遊標提供了一種對從表中檢索出的資料進行操作的靈活手段,就本質而言,遊標實際上是一種能從包括多條資料記錄的結果集中每次提取一條記錄的機制。

上一節的樣本中,我們看到了Cursor,這就是遊標。我們可以簡單的將Cursor理解成指向資料庫中某一行資料的對象。在Android中,查詢資料庫是通過Cursor類來實現的。當我們使用SQLiteDatabase.query()方法時,會得到一個Cursor對象,Cursor指向的就是每一條資料。它提供了很多有關查詢的方法,具體方法如表5-2所示。

方法

傳回值

說明

close()

void

關閉遊標,釋放資源

copyStringToBuffer(int columnIndex, CharArrayBuffer buffer)

void

在緩衝區中檢索請求的列的文本,將將其儲存

getColumnCount()

int

返回所有列的總數

getColumnIndex(String columnName)

int

返回指定列的名稱,如果不存在返回-1

getColumnIndexOrThrow(String columnName)

int

從零開始返回指定列名稱,如果不存在將拋出IllegalArgumentException 異常

getColumnName(int columnIndex)

String

從給定的索引返回列名

getColumnNames()

String[]

返回一個字串數組的列名

getCount()

int

返回Cursor中的行數

moveToFirst()

boolean

移動游標到第一行

moveToLast()

boolean

移動游標到最後一行

moveToNext()

boolean

移動游標到下一行

moveToPosition(int position)

boolean

移動游標到一個絕對的位置

moveToPrevious()

boolean

移動游標到上一行

isBeforeFirst()

boolean

返回遊標是否指向之前第一行的位置

isAfterLast()

boolean

返回遊標是否指向最後一行的位置

isClosed()

boolean

如果返回true即表示該遊標己關閉

表5-2 Cursor的方法

 

    由於上一節的程式碼範例中已經包含了Cursor的簡單使用的例子,這裡就不再舉例說明。

聯繫我們

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