Android SQLite詳解及範例程式碼_Android

來源:互聯網
上載者:User

在Android中使用SQLite資料庫的入門指南,打算分下面幾部分與大家一起分享,

1、什麼是SQLite

2、Android中使用SQLite

一、什麼是SQLite

SQLite是一款開源的、輕量級的、嵌入式的、關係型資料庫。它在2000年由D. Richard Hipp發布,可以支援Java、Net、PHP、Ruby、Python、Perl、C等幾乎所有的現代程式設計語言,支援Windows、Linux、Unix、Mac OS、Android、IOS等幾乎所有的主流作業系統平台。

SQLite被廣泛應用的在蘋果、Adobe、Google的各項產品。如果非要舉一個你身邊應用SQLite的例子的話,如果你的機器中裝的有迅雷,請開啟迅雷安裝目錄,搜尋一下sqlite3.dll,是不是找到了它的身影? 如果你裝的有金山詞霸,那麼開啟他的安裝目錄也會看到sqlite.dll的存在。是的,SQLite早就廣泛的應用在我們接觸的各種產品中了,當然我們今天學習它,是因為在Android開發中,Android推薦的資料庫,也是內建了完整支援的資料庫就是SQlite。

SQLite的特性:

1. ACID事務
2. 零配置 – 無需安裝和管理配置
3. 儲存在單一磁碟檔案中的一個完整的資料庫
4. 資料庫檔案可以在不同位元組順序的機器間自由的共用
5. 支援資料庫大小至2TB
6. 足夠小, 大致3萬行C代碼, 250K
7. 比一些流行的資料庫在大部分普通資料庫操作要快
8. 簡單, 輕鬆的API
9. 包含TCL綁定, 同時通過Wrapper支援其他語言的綁定
10. 良好注釋的原始碼, 並且有著90%以上的測試覆蓋率
11. 獨立: 沒有額外依賴
12. Source完全的Open, 你可以用於任何用途, 包括出售它
13. 支援多種開發語言,C, PHP, Perl, Java, ASP.NET,Python

推薦的SQLite用戶端管理工具,Firefox外掛程式 Sqlite Manger

二、Android中使用SQLite

我們還是通過一個例子來學習,相關講解都寫在代碼注釋裡。

1、建立一個項目Lesson15_HelloSqlite,Activity起名叫MainHelloSqlite.java

2、編寫使用者介面 res/layout/main.xml,準備增(insert)刪(delete)改(update)查(select)四個按鈕,準備一個下拉式清單spinner,顯示表中的資料。

<?xml version="1.0" encoding="utf-8"?><linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">    <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/TextView01" android:text="SQLite基本操作">    </textview>    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button01" android:text="增 | insert" android:minwidth="200dp"></button>    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button02" android:text="刪 | delete" android:minwidth="200dp"></button>    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button03" android:text="改 | update" android:minwidth="200dp"></button>    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button04" android:text="查 | select" android:minwidth="200dp"></button>    <spinner android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margintop="5dp" android:id="@+id/Spinner01" android:minwidth="200dp">    </spinner>    <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/TextView02"></textview></linearlayout>

3、在MainHeloSqlite.java的同目錄中建立一個資料庫操作輔助類 DbHelper.java,內容如下:

package android.basic.lesson15;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;public class DbHelper extends SQLiteOpenHelper {    public DbHelper(Context context, String name, CursorFactory factory,            int version) {        super(context, name, factory, version);    }    //輔助類建立時運行該方法    @Override    public void onCreate(SQLiteDatabase db) {        String sql = "CREATE TABLE pic (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , fileName VARCHAR, description VARCHAR)";        db.execSQL(sql);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    }}

4、MainHelloSqlite.java的內容如下:

package android.basic.lesson15;import android.app.Activity;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.Button;import android.widget.SimpleCursorAdapter;import android.widget.Spinner;import android.widget.TextView;import android.widget.Toast;public class MainHelloSqlite extends Activity {    //SQLiteDatabase對象    SQLiteDatabase db;    //資料庫名    public String db_name = "gallery.sqlite";    //表名    public String table_name = "pic";    //輔助類名    final DbHelper helper = new DbHelper(this, db_name, null, 1);    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        //UI組件        Button b1 = (Button) findViewById(R.id.Button01);        Button b2 = (Button) findViewById(R.id.Button02);        Button b3 = (Button) findViewById(R.id.Button03);        Button b4 = (Button) findViewById(R.id.Button04);        //從輔助類獲得資料庫物件        db = helper.getWritableDatabase();        //初始化資料        initDatabase(db);        //更新下拉式清單中的資料        updateSpinner();        //定義按鈕點擊監聽器        OnClickListener ocl = new OnClickListener() {            @Override            public void onClick(View v) {                //ContentValues對象                ContentValues cv = new ContentValues();                switch (v.getId()) {                //添加按鈕                case R.id.Button01:                    cv.put("fileName", "pic5.jpg");                    cv.put("description", "圖片5");                    //添加方法                    long long1 = db.insert("pic", "", cv);                    //添加成功後返回行號,失敗後返回-1                    if (long1 == -1) {                        Toast.makeText(MainHelloSqlite.this,                                "ID是" + long1 + "的圖片添加失敗!", Toast.LENGTH_SHORT)                                .show();                    } else {                        Toast.makeText(MainHelloSqlite.this,                                "ID是" + long1 + "的圖片添加成功!", Toast.LENGTH_SHORT)                                .show();                    }                    //更新下拉式清單                    updateSpinner();                    break;                //刪除描述是'圖片5'的資料行                case R.id.Button02:                    //刪除方法                    long long2 = db.delete("pic", "description='圖片5'", null);                    //刪除失敗返回0,成功則返回刪除的條數                    Toast.makeText(MainHelloSqlite.this, "刪除了" + long2 + "條記錄",                            Toast.LENGTH_SHORT).show();                    //更新下拉式清單                    updateSpinner();                    break;                //更新檔案名稱是'pic5.jpg'的資料行                case R.id.Button03:                    cv.put("fileName", "pic0.jpg");                    cv.put("description", "圖片0");                    //更新方法                    int long3 = db.update("pic", cv, "fileName='pic5.jpg'", null);                    //刪除失敗返回0,成功則返回刪除的條數                    Toast.makeText(MainHelloSqlite.this, "更新了" + long3 + "條記錄",                            Toast.LENGTH_SHORT).show();                    //更新下拉式清單                    updateSpinner();                    break;                //查詢當前所有資料                case R.id.Button04:                    Cursor c = db.query("pic", null, null, null, null,                            null, null);                    //cursor.getCount()是記錄條數                    Toast.makeText(MainHelloSqlite.this,                            "當前共有" + c.getCount() + "條記錄,下面一一顯示:",                            Toast.LENGTH_SHORT).show();                    //迴圈顯示                    for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){                        Toast.makeText(MainHelloSqlite.this,                                "第"+ c.getInt(0) +"條資料,檔案名稱是" + c.getString(1) + ",描述是"+c.getString(2),                                Toast.LENGTH_SHORT).show();                    }                    //更新下拉式清單                    updateSpinner();                    break;                }            }        };        //給按鈕綁定監聽器        b1.setOnClickListener(ocl);        b2.setOnClickListener(ocl);        b3.setOnClickListener(ocl);        b4.setOnClickListener(ocl);    }    //初始化表    public void initDatabase(SQLiteDatabase db) {        ContentValues cv = new ContentValues();        cv.put("fileName", "pic1.jpg");        cv.put("description", "圖片1");        db.insert(table_name, "", cv);        cv.put("fileName", "pic2.jpg");        cv.put("description", "圖片2");        db.insert(table_name, "", cv);        cv.put("fileName", "pic3.jpg");        cv.put("description", "圖片3");        db.insert(table_name, "", cv);        cv.put("fileName", "pic4.jpg");        cv.put("description", "圖片4");        db.insert(table_name, "", cv);    }    //更新下拉式清單    public void updateSpinner() {        //定義UI組件        final TextView tv = (TextView) findViewById(R.id.TextView02);        Spinner s = (Spinner) findViewById(R.id.Spinner01);        //從資料庫中擷取資料放入遊標Cursor對象        final Cursor cursor = db.query("pic", null, null, null, null, null,                null);        //建立簡單遊標匹配器        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,                android.R.layout.simple_spinner_item, cursor, new String[] {                        "fileName", "description" }, new int[] {                        android.R.id.text1, android.R.id.text2 });        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);        //給下拉式清單設定匹配器        s.setAdapter(adapter);        //定義子項目選擇監聽器        OnItemSelectedListener oisl = new OnItemSelectedListener() {            @Override            public void onItemSelected(AdapterView<?> parent, View view,                    int position, long id) {                cursor.moveToPosition(position);                tv.setText("當前pic的描述為:" + cursor.getString(2));            }            @Override            public void onNothingSelected(AdapterView<?> parent) {            }        };        //給下拉式清單綁定子項目選擇監聽器        s.setOnItemSelectedListener(oisl);    }    //視窗銷毀時刪除表中資料    @Override    public void onDestroy() {        super.onDestroy();        db.delete(table_name, null, null);        updateSpinner();    }}

5、運行程式,查看結果:

本例使用的是SQLiteDatabase已經封裝好的insert,delete,update,query方法,感興趣的同學可以用SQLiteDatabase的execSQL()方法和rawQuery()方法來實現。好本講就到這裡。

聯繫我們

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