Android數據存儲——SQLite數據庫存儲

AndroidSQLite

  完整代碼請見:longlong’s github
  效果圖:



SQLiteOpenHelper抽象類

  • 含有兩個抽象方法:onCreate()方法和onUpgrade()方法 需要重寫,並在這兩個方法中去創建升級數據庫
  • 含有兩個重要的實例方法:getReadableDatabase()和getWritableDatabase() 這兩個方法都可以創建或打開一個現有的數據庫(如果數據庫已存在則直接打開,否則創建一個新的數據庫),並返回一個可對數據庫進行讀寫操作的對象

      創建數據庫表

create table Book (
id integer primary key autoincrement,
author text,
price real,
pages integer,
name text)

  integer整型 real浮點型 text文本類型 blob二進制類型 primary key設id爲主鍵 autoincrement表示id列是增長的。

創建數據庫和數據庫表

1.新建MyDatabaseHelper類繼承自SQLiteOpenHelper

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)";
            private Context mContext;

            //SQLiteOpenHelper中用參數少一點的那個構造方法,接收四個參數:
            //Context,必須要有它才能對數據庫進行操作。
            //數據庫名,創建數據庫時使用的就是這裏指定的名稱。
            //允許我們在查詢數據的時候返回一個自定義的Cursor,一般都是傳入null。
            //當前數據庫的版本號,可用於對數據庫進行升級操作。
            //構建出SQLiteOpenHelper的實例之後,再調用它的getReadableDatabase()或getWritableDatabase()方法就能夠創建數據庫。
            //數據庫文件會存放在/data/data/<package name>/databases/目錄下。此時,重寫的onCreate()方法也會得到執行,所以通常會在這裏去處理一些創建表的邏輯。
            public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
                super(context, name, factory, version);
                mContext = context;
            }
            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL(CREATE_BOOK);
                Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            }
        }

2.修改MainActivity中的代碼

public class MainActivity extends Activity {
            private MyDatabaseHelper dbHelper;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                //構建出SQLiteOpenHelper的實例,版本號爲1
                dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
                Button createDatabase = (Button) findViewById(R.id.create_database);
                createDatabase.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dbHelper.getWritableDatabase();
                    }
                });
            }
        }

  當第一次點擊按鈕時,就會檢測到當前程序中並沒有BookStore.db這個數據庫,於是會創建該數據庫並調用MyDatabaseHelper中的onCreate()方法,這樣Book表也就得到了創建,然後會彈出一個Toast提示創建成功。再次點擊按鈕時,會發現此時已經存在BookStore.db數據庫了,因此不會再創建一次。

升級數據庫

1.在MyDatabaseHelper中添加建表語句

public static final String CREATE_CATEGORY = "create table Category ("
+ "id integer primary key autoincrement, "
+ "category_name text, "
+ "category_code integer)";

2.onCreate()方法中添加:

db.execSQL(CREATE_CATEGORY);

3.onUpgrade方法中:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//先執行兩條DROP語句
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}

4.MainActivity中:

//傳入一個比1大的數,就可以讓onUpgrade()方法得到執行
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);

添加數據 更新數據和刪除數據

  SQLiteDatabase中提供了一個insert()方法用於添加數據(點擊事件中:)

SQLiteDatabase db = dbHelper.getWritableDatabase();
//ContentValues對象,它提供了一系列的put()方法重載,用於向ContentValues中添加數據。
ContentValues values = new ContentValues();
// 開始組裝第一條數據
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
......

  SQLiteDatabase中提供了update()方法用於對數據進行更新

SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name = ?", new String[] { "The Da Vinci Code" });

  update方法:?是一個佔位符,可以通過第四個參數提供的一個字符串數組爲第三個參數中的每個佔位符指定相應的內容。因此上述代碼想表達的意圖就是,將名字是The Da Vinci Code的這本書的價格改成10.99。
  SQLiteDatabase中提供了一個delete()方法專門用於刪除數據:

db.delete("Book", "pages > ?", new String[] { "500" });

查詢數據

SQLiteDatabase db = dbHelper.getWritableDatabase();
// 查詢Book表中所有的數據
        Cursor cursor = db.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"));
            } while (cursor.moveToNext());
        }
        cursor.close();

  other ways:

//添加數據的方法如下:
db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
new String[] { "The Da Vinci Code", "Dan Brown", "454", "16.96" });
db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
new String[] { "The Lost Symbol", "Dan Brown", "510", "19.95" });
//更新數據的方法如下:
db.execSQL("update Book set price = ? where name = ?", new String[] { "10.99", "The Da Vinci Code" });
//刪除數據的方法如下:
db.execSQL("delete from Book where pages > ?", new String[] { "500" });
//查詢數據的方法如下:
db.rawQuery("select * from Book", null);

  使用事務:要保證刪除舊數據和添加新數據的操作必須一起完成:

SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction(); // 開啓事務
        try {
            db.delete("Book", null, null);
            ContentValues values = new ContentValues();
            values.put("name", "Game of Thrones");
            values.put("author", "George Martin");
            values.put("pages", 720);
            values.put("price", 20.85);
            db.insert("Book", null, values);
            db.setTransactionSuccessful(); // 事務已經執行成功
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction(); // 結束事務
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章