天天看點

Android開發 | 使用SQLite存儲資料

Android開發 | 使用SQLite存儲資料

大家好,我是中國碼農綠茶哥哥。

歡迎關注我的個人微信公衆号:康元路8号!

一、前言

Android 為了讓我們能夠更加友善地管理資料庫,專門提供了一個 SQLiteOpenHelper 幫助

類,借助這個類就可以經常簡單地對資料庫進⾏建立和更新。

首先我們要知道 SQLiteOpenHelper 是一個抽象類,這意味着如果我們想要使用它的話,就需要建立一個自己的幫助類去繼承它。 SQLiteOpenHelper 中有兩個抽象方法,分别是

onCreate()

onUpgrade()

,我們必須在自己的幫助類裡面重寫這兩個方法,然後分别在這兩個方法中去實作建立、更新資料庫的邏輯。

SQLiteOpenHelper 中還有兩個非常重要的執行個體方法 ,getReadableDatabase() 和 getWritableDatabase() 。這兩個方法都可以建立或打開一個現有的資料庫(如果資料庫已存在則直接打開,否則建立一個新的資料庫),并傳回一個可對資料庫進行讀寫操作的對象。

不同的是,當資料庫不可寫入的時候(如磁盤空間已滿)

getReadableDatabase()

方法傳回的對象将以隻讀的方式去打開資料庫,而

getWritableDatabase()

方法則将出現異常。SQLiteOpenHelper 中有兩個構造方法可供重寫。

這個構造方法中接收四個參數:

  • Context

    ,這個沒什麼好說的,必須要有它才能對資料庫進行操作
  • 資料庫名,建立資料庫時使用的就是這個指定的名稱
  • 允許我們在查詢資料的時候傳回一個自定義的

    Cursor

    ,一般都是傳回null
  • 表示目前資料庫的版本号, 可用于對資料庫進行更新操作

建構出 SQLiteOpenHelper 的執行個體之後,再調用它的

getReadableDatabase()

getWritableDatabase()

方法就能夠建立資料庫了,資料庫檔案會存放在

/data/data/<package name>/databases/

目錄下。此時, 重寫的

onCreate()

方法也會得到執行, 是以通常會在這裡去處理一些建立表的邏輯。

二、案例一

項目截圖

Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料

主要功能

  1. 建立文本内容
  2. 長按條目選擇編輯或删除

三、案例二

運用了Android SQLite的經典使用方法,這裡直接貼上代碼

MyDatabaseHelper.java:

public class MyDatabaseHelper extends SQLiteOpenHelper {
    public static final String CREATE_BOOK = "create table book ("
            + "id integer primary key autoincrement, "
            + "author text, "
            + "price real, "
            + "pages integer, "
            + "name text)";
    public static final String CREATE_CATEGORY = "create table Category("
            + "id integer primary key autoincrement,"
            + "category_name text,"
            + "category_code integer)";
    private Context mContext;
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext, "建立book資料表成功!", Toast.LENGTH_SHORT).show();
        Toast.makeText(mContext, "建立Category表成功!", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }
}
           

MainActivity.java:

public class MainActivity extends AppCompatActivity {
    private MyDatabaseHelper dbHelper;
    private Button createDatabase, add_data, update_btn,
            delete_btn, query_btn, replace_btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //執行個體化一個dbHelper對象
       dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 3);
        //初始化UI控件
        createDatabase = (Button) findViewById(R.id.create_database);
        add_data = (Button) findViewById(R.id.add_data);
        update_btn = (Button) findViewById(R.id.update_data);
        delete_btn = (Button) findViewById(R.id.delete_data);
        query_btn = (Button) findViewById(R.id.query_data);
        replace_btn= (Button) findViewById(R.id.replace_data);
        //按鈕createDatabase的監聽響應事件
        createDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper.getWritableDatabase();
            }
        });
        //添加資料表資料
        add_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                //開始組裝第一條資料
                values.put("name", "The Yaowen Code");
                values.put("author", "YaoWen");
                values.put("pages", "454");
                values.put("price", "19.50");
                //插入第一條資料
                db.insert("book", null, values);
                //開始組裝第二條資料
                values.put("name", "The Siny Code");
                values.put("author", "Siny");
                values.put("pages", "459");
                values.put("price", "39.50");
                //插入第二條資料
                db.insert("book", null, values);
                //開始組裝第三條資料
                values.put("name", "The HTML5 Code");
                values.put("author", "Siny");
                values.put("pages", "678");
                values.put("price", "59.50");
                //插入第三條資料
                db.insert("book", null, values);
                //開始組裝第四條資料
                values.put("name", "The C# Code");
                values.put("author", "HelloWorld");
                values.put("pages", "897");
                values.put("price", "29.50");
                //插入第四條資料
                db.insert("book", null, values);
            }
        });
        //更新資料表資料
        update_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                //更新第一條資料
                contentValues.put("name", "The Java Code");
                db.update("book", contentValues, "author=?", new String[]{
                        "Siny"
                });
                //更新第二條資料
                contentValues.put("name", "The Android Code");
                db.update("book", contentValues, "author=?", new String[]{
                        "YaoWen"
                });
            }
        });
        //删除資料表資料
        delete_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase database = dbHelper.getWritableDatabase();
                database.delete("book", "pages>?", new String[]{"500"});
            }
        });
        //查詢資料表資料
        query_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase database = dbHelper.getWritableDatabase();
                //查詢book資料表裡的所有資料;
                Cursor cursor = database.query("book", null, null, null, null, null, null);
                if (cursor.moveToFirst()) {
                    do {
                        //周遊Cursor對象,取出資料并列印
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        String author = cursor.getString(cursor.getColumnIndex("author"));
                        int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                        double price = cursor.getDouble(cursor.getColumnIndex("price"));
                        Log.d("MyLog","--------------------");
                        Log.d("MyLog","書名是:"+name);
                        Log.d("MyLog","作者是:"+author);
                        Log.d("MyLog","編号是:"+pages);
                        Log.d("MyLog","價格是:"+price);
                        Log.d("MyLog","--------------------");
                    }while (cursor.moveToNext());
                }
                cursor.close();
            }
        });
        //測試資料庫的事務功能
        replace_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase database = dbHelper.getWritableDatabase();
                database.beginTransaction();//開啟事務
                try {
                    database.delete("book", null, null);
                    if (true) {
                        //這裡抛出一個異常,讓事務失敗
                        throw new NullPointerException();
                    }
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("name", "Game of Thrones");
                    contentValues.put("author", "HelloWorld");
                    contentValues.put("pages", 720);
                    contentValues.put("price", 21.85);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    database.endTransaction();//結束事務
                }
            }
        });
    }
}
           

main_activity.xml:

```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/create_database"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="建立資料庫" />
    <Button
        android:id="@+id/add_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加資料" />
    <Button
        android:id="@+id/update_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="更新資料" />
    <Button
        android:id="@+id/delete_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除資料" />
    <Button
        android:id="@+id/query_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查詢資料" />
    <Button
        android:id="@+id/replace_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="替換資料(事務)"
        />
</LinearLayout>
           

四、項目位址

GitHub - SQLiteDemo

Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料
Android開發 | 使用SQLite存儲資料

整理不易,歡迎

Star

Fork

_ ,謝謝~~

Android開發 | 使用SQLite存儲資料