Android資料庫SQLite

來源:互聯網
上載者:User

標籤:

資料庫資料庫增刪改查

添加

insert into info (name,phone) values (‘zhangsan‘,‘110‘)

刪除

delete from info where name=‘zhangsan‘

修改

update info set phone =‘999‘ where name =‘zhangsan‘

查詢

select * from info where name=‘zhangsan‘

Android下資料庫增刪改查
  • void - db.execSQL() 增刪改
  • cursor - db.rawQuery() 查詢

注意:操作資料庫 一定要記得把資料庫**串連**給關閉掉。 cursor 用完後,也記得關閉

getReadableDatabase() getWriteableDatabase()返回的是同一個資料庫的執行個體, 區別就是資料庫返回的時候是否加鎖。

利用sqlite3工具查看資料庫的內容

sqlite3 xxx.db

如果出現中文亂碼 需要修改cmd的編碼集

65001 utf-8

chcp 65001 更改cmd視窗的編碼,預設是gb2312

Android下建立資料庫步驟
  1. 類繼承SQLiteOpenHelper(資料建立的協助類,oncreate,onUpgrade)

產生構造方法

        /**     * 建立一個資料庫協助類,去建立/開啟/管理 資料庫     * @param context   上下文     * @param name  設定資料庫名稱     * @param factory   CursorFactory 定義一個結果集,遊標工廠。     *                      Cursor 遊標(結果集,儲存了對資料庫的引用,指標)     *                      設定為null,表示調用預設遊標             * @param version   資料庫的版本,從1開始     */    public MySqliteDB(Context context, String name, CursorFactory factory,            int version) {        super(context, name, factory, version);        // TODO Auto-generated constructor stub    }
  1. 重寫onCreate(SQLiteDatabase db)方法 ,資料庫第一次被建立的時候調用的方法。適合資料庫表結構的初始化.

    create table info (_id integer primary key autoincrement, name varchar(20), phone varchar(20))

  2. 重寫onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion),資料庫被更新的時候調用的方法.資料庫的版本號碼增加的時候調用。

  3. 添加helper類的構造方法。 指定資料庫的名稱,版本號碼,遊標工廠預設null
資料庫檔案建立的位置

/data/data/包名/databases/xxx.db

資料庫在建立的時候不指定裡面的內容,預設建立只有一張表 metadata儲存系統語言環境。

Cursor 遊標
  • 儲存了對資料庫的引用,指標。設定為null,表示調用預設遊標。
  • 預設起始位置為-1
  • 常用方法:

    boolean move(int offset)       Move the cursor by a relative amount, forward or backward, from the current position.  boolean moveToFirst()       Move the cursor to the first row.  boolean moveToLast()       Move the cursor to the last row.  boolean moveToNext()       Move the cursor to the next row.  boolean moveToPosition(int position)       Move the cursor to an absolute position.  boolean moveToPrevious()       Move the cursor to the previous row. 
如何防止SQL語句注入

方法:綁定參數

//樣本xx.exeSQL("insert into person(name,age) values (?,?)",new Object[]{name,age})
sqlite3的命令
  • sqlite3 <資料庫名> 查看資料庫,進入sqlite模式
  • .tables 查看所有表
  • .mode column | list | insert | line | tabs | tcl | csv 改變輸出格式
  • .schema 查看庫中所有表的DDL語句
  • .headers on/off 顯示表頭 預設off
  • .nullValueNULL 空值資料顯示問題
  • .dump<表名> 產生形成表的SQL指令碼
  • .dump 產生整個資料庫的SQL指令碼
  • .exit 退出
  • .help 查看協助
(重點)類 SQLiteDatabase(API實現資料庫的正刪改查)

插入資料

 long insert(String table, String nullColumnHack, ContentValues values)           Convenience method for inserting a row into the database. 

刪除資料

 int delete(String table, String whereClause, String[] whereArgs)           Convenience method for deleting rows in the database. 

修改資料

 int update(String table, ContentValues values, String whereClause, String[] whereArgs)           Convenience method for updating rows in the database. 

查詢資料

 Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)           Query the given URL, returning a Cursor over the result set.  Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)           Query the given table, returning a Cursor over the result set.  Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)           Query the given table, returning a Cursor over the result set. 
兩種增刪改查方法的優缺點
  • 自己寫sql語句
    • 自由度高,靈活
    • 效率高,資源佔用小
    • 可以實現表的級聯查詢
  • google的現成API
    • 方便,不易出錯
    • 資源開銷比較大,效率稍低
      • 有傳回值
(重點)資料庫的事務

優點:安全,高效

保證操作要麼同時成功,要麼同時失敗。 銀行轉賬

A->B 匯款 A - 100塊 B + 100塊

事務的模板代碼

      //開啟事務      db.beginTransaction();       try {         ...         處理商務邏輯A         ...         //設定成功(復原)點,即要麼全成功要麼全失敗         db.setTransactionSuccessful();         ...         處理商務邏輯B         ...         //設定成功(復原)點。(同時操作若干個動作時可以設定多個成功點)         db.setTransactionSuccessful();         ...       } finally {        //結束事務         db.endTransaction();        //千萬不要忘記幹掉這個        db.close();       }
(重點)資料庫的內容同步顯示到介面(ListView)。listview工作的原理

mvc 設計模式。 * model 資料模型 Person * view 視圖 ListView * controller 控制器 Adapter 資料配接器,將資料集合以特定的方式組織到介面上

自己理解: ListView + Adapter機制,在需要的時候去建立TextView對象 根據當前螢幕可顯示的條數去建立對象,顯示過去(之前在螢幕中出現,然後又消失的條目)的條目對象會被重新賦予新值(即顯示出的新的條目)

Listview 使用步驟
  • 寫ui介面 xml檔案 ListView
  • 尋找listview
  • 實現listview的資料配接器 adapter
  • 給listview設定adapter,一旦設定了adapter,就會從這個方法索要View
開發的時候如何自訂資料配接器,實現複雜的ui介面。
  • 定義listview布局
  • 尋找listview
  • 自訂一個複雜BaseAdapter
    • getCount();返回有多少個條目 List.SIZE()
    • getView();返回每個條目的view對象

      定義一個xml檔案 View view = View.inflate(MainActivity.this, R.layout.rl_item, null); 修改view對象裡面子孩子顯示的內容 view.findViewById();

  • 給listview設定adapter
(重點)打氣筒——LayoutInflater

如何將XML資料(布局檔案)轉換成View對象? 將一個XML的布局檔案填充成一個View對象,以便添加到其他 View容器中。

SimpleAdapter —— 顯示圖片文本資訊 ArrayAdapter —— 只能顯示圖片

Android對話方塊

Builder

  • 通知對話方塊

  • 列表對話方塊

  • 單選對話方塊

  • 多選對話方塊

ProgressDialog * 進度對話方塊

整理補充:內容提供者

資料庫檔案 一般是私人的。 -rw-rw- --- 別的應用程式是沒辦法訪問私人的資料庫。

目的: 保證應用程式資料的安全。每個應用程式都是獨立的,不可以操作另外一個應用程式資料庫的資料。

有一些特殊的需求,需要把自己私人的資料庫暴露給別的應用程式讓別的應用程式訪問。

內容提供者就是做這個事情的。

內容提供者建立的步驟 ( 理解原理
  • DaYifuProvider extend ContentProvider
  • 在資訊清單檔.xml裡面配置 內容提供者。配置完整類路徑,主機名稱。 android:name="com.itheima.db.DaYifuProvider" android:authorities="com.itheima.db.persondb"
  • DaYifuProvider 定義出來一些資料操作的uri 利用uriMatcher 指定一些特殊的路徑 content://com.itheima.db.persondb/query 查詢 content://com.itheima.db.persondb/insert 添加 content://com.itheima.db.persondb/delete 刪除 content://com.itheima.db.persondb/update 更新
  • 實現DaYifuProvider 增刪改查的方法。 根據業務需求去實現。 實現了query方法, 1.檢查路徑uri是否正確。 2.如果正確返回cursor 3.如果不正確拋出異常。
如何使用內容提供者查詢資料
  1. 擷取內容提供者的解析器 ContentResolver resolver = getContentResolver();
  2. 使用resolver進行增刪改查的操作。

Android資料庫SQLite

聯繫我們

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