Android數據保存之SQLiteDatabase

閒話少聊,這篇文章主要參考了Google的官方文檔

轉載請註明出處
[我的博客]http://www.lostbug.com

首先要創建SQLiteDatabase

這段代碼段定義了單個表格的表格名稱和列名稱

public final class FeedReaderContract {
    // To prevent someone from accidentally instantiating the contract class,
    // give it an empty constructor.
    public FeedReaderContract() {}

    /* Inner class that defines the table contents */
    public static abstract class FeedEntry implements BaseColumns {
        public static final String TABLE_NAME = "entry";
        public static final String COLUMN_NAME_ENTRY_ID = "entryid";
        public static final String COLUMN_NAME_TITLE = "title";
        public static final String COLUMN_NAME_SUBTITLE = "subtitle";
        ...
    }
}

Note: By implementing the BaseColumns interface, your inner class can inherit a primary key field called _ID that some Android classes such as cursor adaptors will expect it to have. It’s not required, but this can help your database work harmoniously with the Android framework.

Create a Database Using a SQL Helper,通過SQL Helper來創建Database

Once you have defined how your database looks, you should implement methods that create and maintain the database and tables. Here are some typical statements that create and delete a table:
一旦你確定了你要建立的數據庫模式,你需要繼承方法來創建和維護你的數據庫表格,下面是創建和刪除數據庫表格的典型語句:

private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
    "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
    FeedEntry._ID + " INTEGER PRIMARY KEY," +
    FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
    FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
    ... // Any other options for the CREATE command
    " )";

private static final String SQL_DELETE_ENTRIES =
    "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;

SQLiteOpenHelper 類中有一組有用的 API。當您使用此類獲取對您數據庫的引用時,系統將只在需要之時而不是 應用啓動過程中執行可能長期運行的操作:創建和更新數據庫。 您只需調用 getWritableDatabase() 或 getReadableDatabase()。

注意:由於它們可能長期運行,因此請確保您在後臺線程中調用 getWritableDatabase() 或 getReadableDatabase() , 比如使用 AsyncTask 或 IntentService。

創建一個繼承SQLiteOpenHelper的類

public class FeedReaderDbHelper extends SQLiteOpenHelper {
    // If you change the database schema, you must increment the database version.
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "FeedReader.db";

    public FeedReaderDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}

要訪問您的數據庫,請實例化 的子類:

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());

通過SQLiteOpenHelper的getWritableDatabase()或者getReadableDatabase()方法獲取數據庫的實例:

SQLiteDatabase db = mFeedReaderDbHelper.getWritableDatabase();//可修改
SQLiteDatabase db = mFeedReaderDbHelper.getReadableDatabase();//只讀

接下來就是數據庫的維護處理了

數據庫的相關操作無非讀、寫、刪、改四板斧而已

  • 寫 insert
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();

// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
         FeedEntry.TABLE_NAME,//數據庫名稱
         FeedEntry.COLUMN_NAME_NULLABLE,//無數據時,默認填充值
         values);//填充值
  • 改 update
SQLiteDatabase db = mDbHelper.getReadableDatabase();

// New value for one column
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

// Which row to update, based on the ID
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };

int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,//數據庫名稱
    values,////要更新的數據
    selection,//選中列(個人理解)
    selectionArgs);//更新行在這列中的內容
  • 刪 delete
// Define 'where' part of query.
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
// Specify arguments in placeholder order.
String[] selectionArgs = { String.valueOf(rowId) };
// Issue SQL statement.
db.delete(table_name, //數據庫名稱
 selection,//選中列
 selectionArgs);//刪除行在這列中的內容
  • 讀 query
SQLiteDatabase db = mDbHelper.getReadableDatabase();

// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
    FeedEntry._ID,
    FeedEntry.COLUMN_NAME_TITLE,
    FeedEntry.COLUMN_NAME_UPDATED,
    ...
    };

// How you want the results sorted in the resulting Cursor
String sortOrder =
    FeedEntry.COLUMN_NAME_UPDATED + " DESC";

Cursor c = db.query(
    FeedEntry.TABLE_NAME,  // The table to query 數據庫名稱
    projection,            // The columns to return 用於指定去查詢哪幾列
    selection,             // The columns for the WHERE clause
    selectionArgs,         // The values for the WHERE clause  查詢某一行或某幾行的數據
    null,                  // don't group the rows 指定需要去group by 的列
    null,                  // don't filter by row groups 對group by之後的數據進行進一步的過濾
    sortOrder              // The sort order 指定查詢結果的排序方式
    ); 
cursor.moveToFirst();
long itemId = cursor.getLong(
    cursor.getColumnIndexOrThrow(FeedEntry._ID)
);

到此爲止吧,不寫了

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