Android数据存储方案 -- SQLite数据库存储

Android也为本地存储提供了轻量级的数据库存储方案 -- SQLite数据库存储。

生成的数据库文件存放在\data\data\com.xxx.test\databases\, 可以使用以下命令查询生成的database。

假设database名称为BookStore.db, 表的名称是Book。

进入adb shell,然后进入数据库存放的位置\data\data\com.xxx.test\databases\。

输入命令"sqlite3 BookStore.db", 即可进入sqlite的交互模式,常用命令如下,

1. 查询表: sqlite> .table

2. 查询表的生成命令:sqlite> .schema

3. 查询表中的内容:sqlite> select * from Book;

4. 获取命令帮助:sqlite> .help

通过上面的命令,我们就可以知道我们创建的数据库/表格是否正确。

 

我们首先要创建一个新类,继承SQLiteOpenHelper. 注意里面的onUpgrade()方法,如果要更改数据库的表格结构,需要先删除之前的表格,才能更改原先的数据库设计,这对于数据敏感性的程序,需要做数据库的备份然后在升级数据库结构。

package com.xxx.testsqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class MyDatebaseHelper extends SQLiteOpenHelper {
    private static final String TAG = "TestSQLite";

    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 MyDatebaseHelper(Context context, String name,
                            SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
        Log.d(TAG, "MyDatebaseHelper: start");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "onCreate: start");
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "onUpgrade: start");
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }
}

我们可以在主Activity的onCreate()方法中,创建并初始化数据库,参考代码如下,


    private MyDatebaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new MyDatebaseHelper(this, "BookStore.db", null, 2);
    }

下面是数据库的增加/修改/删除/查询的代码,


    private void addData() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        ContentValues values = new ContentValues();

        // The 1st data
        values.put("name", "The Da Vinci Code");
        values.put("author", "Dan Brown");
        values.put("pages", 454);
        values.put("price", 16.96);
        db.insert("Book", null, values);

        values.clear();

        // The 2nd data
        values.put("name", "The Lost Symbol");
        values.put("author", "Dan Brown");
        values.put("pages", 510);
        values.put("price", 19.35);
        db.insert("Book", null, values);
    }

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

    private void deleteData() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("Book", "pages > ?", new String[] {"500"});
    }

    private void queryData() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // Query all of the data in the table "Book"
        Cursor cursor = db.query("Book", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                // Go through the Cursor object, and print the data
                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(TAG, "queryData: book name is " + name);
                Log.d(TAG, "queryData: book author is " + author);
                Log.d(TAG, "queryData: book pages is " + pages);
                Log.d(TAG, "queryData: book price is " + price);
            }while (cursor.moveToNext());
        }
        cursor.close();
    }

有了数据库的支持,Android的处理能力更加强大。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章