欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android SQLite詳解及示例代碼

 更新時間:2016年08月10日 09:52:31   作者:chino  
本文主要講解Android SQLite,這里對數(shù)據(jù)庫SQLite 做了詳細的知識資料整理,并附示例代碼和實現(xiàn)效果圖,有需要的小伙伴可以參考下

在Android中使用SQLite數(shù)據(jù)庫的入門指南,打算分下面幾部分與大家一起分享,

1、什么是SQLite

2、Android中使用SQLite

一、什么是SQLite

SQLite是一款開源的、輕量級的、嵌入式的、關(guān)系型數(shù)據(jù)庫。它在2000年由D. Richard Hipp發(fā)布,可以支援Java、Net、PHP、Ruby、Python、Perl、C等幾乎所有的現(xiàn)代編程語言,支持Windows、Linux、Unix、Mac OS、Android、IOS等幾乎所有的主流操作系統(tǒng)平臺。

SQLite被廣泛應(yīng)用的在蘋果、Adobe、Google的各項產(chǎn)品。如果非要舉一個你身邊應(yīng)用SQLite的例子的話,如果你的機器中裝的有迅雷,請打開迅雷安裝目錄,搜索一下sqlite3.dll,是不是找到了它的身影? 如果你裝的有金山詞霸,那么打開他的安裝目錄也會看到sqlite.dll的存在。是的,SQLite早就廣泛的應(yīng)用在我們接觸的各種產(chǎn)品中了,當然我們今天學(xué)習它,是因為在Android開發(fā)中,Android推薦的數(shù)據(jù)庫,也是內(nèi)置了完整支持的數(shù)據(jù)庫就是SQlite。

SQLite的特性:

1. ACID事務(wù)
2. 零配置 – 無需安裝和管理配置
3. 儲存在單一磁盤文件中的一個完整的數(shù)據(jù)庫
4. 數(shù)據(jù)庫文件可以在不同字節(jié)順序的機器間自由的共享
5. 支持數(shù)據(jù)庫大小至2TB
6. 足夠小, 大致3萬行C代碼, 250K
7. 比一些流行的數(shù)據(jù)庫在大部分普通數(shù)據(jù)庫操作要快
8. 簡單, 輕松的API
9. 包含TCL綁定, 同時通過Wrapper支持其他語言的綁定
10. 良好注釋的源代碼, 并且有著90%以上的測試覆蓋率
11. 獨立: 沒有額外依賴
12. Source完全的Open, 你可以用于任何用途, 包括出售它
13. 支持多種開發(fā)語言,C, PHP, Perl, Java, ASP.NET,Python

推薦的SQLite客戶端管理工具,火狐插件 Sqlite Manger

二、Android中使用SQLite

我們還是通過一個例子來學(xué)習,相關(guān)講解都寫在代碼注釋里。

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

2、編寫用戶界面 res/layout/main.xml,準備增(insert)刪(delete)改(update)查(select)四個按鈕,準備一個下拉列表spinner,顯示表中的數(shù)據(jù)。

<?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的同目錄中新建一個數(shù)據(jù)庫操作輔助類 DbHelper.java,內(nèi)容如下:

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的內(nèi)容如下:

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;
    //數(shù)據(jù)庫名
    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);

        //從輔助類獲得數(shù)據(jù)庫對象
        db = helper.getWritableDatabase();

        //初始化數(shù)據(jù)
        initDatabase(db);
        //更新下拉列表中的數(shù)據(jù)
        updateSpinner();

        //定義按鈕點擊監(jiān)聽器
        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'的數(shù)據(jù)行
                case R.id.Button02:
                    //刪除方法
                    long long2 = db.delete("pic", "description='圖片5'", null);
                    //刪除失敗返回0,成功則返回刪除的條數(shù)
                    Toast.makeText(MainHelloSqlite.this, "刪除了" + long2 + "條記錄",
                            Toast.LENGTH_SHORT).show();
                    //更新下拉列表
                    updateSpinner();
                    break;

                //更新文件名是'pic5.jpg'的數(shù)據(jù)行
                case R.id.Button03:

                    cv.put("fileName", "pic0.jpg");
                    cv.put("description", "圖片0");
                    //更新方法
                    int long3 = db.update("pic", cv, "fileName='pic5.jpg'", null);
                    //刪除失敗返回0,成功則返回刪除的條數(shù)
                    Toast.makeText(MainHelloSqlite.this, "更新了" + long3 + "條記錄",
                            Toast.LENGTH_SHORT).show();
                    //更新下拉列表
                    updateSpinner();
                    break;

                //查詢當前所有數(shù)據(jù)
                case R.id.Button04:
                    Cursor c = db.query("pic", null, null, null, null,
                            null, null);
                    //cursor.getCount()是記錄條數(shù)
                    Toast.makeText(MainHelloSqlite.this,
                            "當前共有" + c.getCount() + "條記錄,下面一一顯示:",
                            Toast.LENGTH_SHORT).show();
                    //循環(huán)顯示
                    for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
                        Toast.makeText(MainHelloSqlite.this,
                                "第"+ c.getInt(0) +"條數(shù)據(jù),文件名是" + c.getString(1) + ",描述是"+c.getString(2),
                                Toast.LENGTH_SHORT).show();
                    }
                    //更新下拉列表
                    updateSpinner();
                    break;
                }
            }
        };

        //給按鈕綁定監(jiān)聽器
        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);

        //從數(shù)據(jù)庫中獲取數(shù)據(jù)放入游標Cursor對象
        final Cursor cursor = db.query("pic", null, null, null, null, null,
                null);

        //創(chuàng)建簡單游標匹配器
        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);

        //給下拉列表設(shè)置匹配器
        s.setAdapter(adapter);

        //定義子元素選擇監(jiān)聽器
        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) {
            }
        };

        //給下拉列表綁定子元素選擇監(jiān)聽器
        s.setOnItemSelectedListener(oisl);
    }

    //窗口銷毀時刪除表中數(shù)據(jù)
    @Override
    public void onDestroy() {
        super.onDestroy();
        db.delete(table_name, null, null);
        updateSpinner();
    }
}

5、運行程序,查看結(jié)果:

本例使用的是SQLiteDatabase已經(jīng)封裝好的insert,delete,update,query方法,感興趣的同學(xué)可以用SQLiteDatabase的execSQL()方法和rawQuery()方法來實現(xiàn)。好本講就到這里。

相關(guān)文章

最新評論