Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 數據存儲之 SQLite 數據庫詳解

編輯:關於 Android 程式設計

前言

Android 提供了多種數據存儲方式。少量數據用 SharedPreferences 或文件存儲即可;但當需要讀寫大量數據時,就得用上數據庫了。Android 內置了 SQLite,這是一個真正的輕量級數據庫——沒有後台進程,整個數據庫就對應一個文件,配合 Android 提供的豐富 API,使用起來相當方便。

SQLiteDatabase

Android 用 SQLiteDatabase 對象來管理數據庫,它提供了創建、刪除、執行 SQL 以及各類數據庫管理任務的方法。

SQLiteDatabase 提供了以下靜態方法來打開文件對應的數據庫:

SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags):打開 path 文件代表的數據庫;
SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory):打開或創建(若不存在)file 文件代表的數據庫;
SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory):打開或創建(若不存在)path 文件代表的數據庫。

拿到 SQLiteDatabase 對象後,就可以調用下列方法進行操作:

JAVA 方法 釋義 execSQL(String sql) 執行 SQL 語句
execSQL(String sql, Object[] bindArgs) 執行帶占位符的 SQL 語句
insert(String table, String nullColumnHack, ContentValues values) 插入數據
delete(String table, String whereClause, String[] whereArgs) 刪除數據
update(String table, ContentValues values, String whereClause, String[] whereArgs) 更新數據
query(...) 查詢數據(多個重載,支持分組、排序、分頁)
rawQuery(String sql, String[] selectionArgs) 執行帶占位符的查詢
beginTransaction() 開始事務
endTransaction() 結束事務

這些方法本意是幫開發者更「簡便」地增刪改查,但其實它們都能用 SQL 語句完成。與其去記那一長串參數,不如把時間花在掌握 SQL 上。

上述查詢方法都會返回一個 Cursor 接口,它提供對查詢結果集的隨機讀寫訪問,並提供以下方法移動記錄指針:

JAVA 方法 釋義 move(int offset) 向前或向後移動指針
moveToFirst() 移到第一行
moveToLast() 移到最后一行
moveToNext() 移到下一行
moveToPrevious() 移到上一行
moveToPosition(int position) 移到指定行
isFirst() / isLast() 是否指向首/尾行
isBeforeFirst() / isAfterLast() 是否在首行前/尾行後
isNull(int columnIndex) 指定列是否為空
isClosed() 游標是否已關閉
getCount() 總數據項數
getPosition() 當前游標指向的行數
getColumnIndex(String columnName) 列名對應的索引
getString(int columnIndex) 當前行指定列的值

移動到指定行後,就能調用 getXXX() 系列方法取出各列數據。

創建數據庫和表

創建數據庫:

 // 判斷數據庫文件所在文件夾是否存在,不存在則創建
 String mPath = Environment.getExternalStorageDirectory() + "/db/";
 File file = new File(mPath);
 if (!file.exists() && !file.isDirectory()) {
     file.mkdirs();
 }
 // 使用靜態方法打開數據庫(不存在則創建),第二個參數為 Cursor 工廠,null 表示默認
 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(mPath + "blog.db", null);

創建表:

 // 執行創建表 SQL,創建名為 blog_info 的表
 String createSql = "create table blog_info(blog_id integer primary key, blog_name varchar(255), blog_link varchar(255))";
 database.execSQL(createSql);

注意:數據庫建在 SD 卡中,需要加上寫入 SD 卡的權限。

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

操作數據庫

建好數據庫和表後,就能管理表中數據了。既可直接用 execSQL() 執行 SQL,也可用 Android 封裝好的增刪改查方法。

insert

insert(String table, String nullColumnHack, ContentValues values):
table:目標表名;
nullColumnHack:當 values 為空時,用來強制插入 null 的列名;
values:一行記錄的數據。
插入參數用 ContentValues,它類似 Map,通過 put(String key, XXX value) 存入,key 為列名。

 ContentValues contentValues = new ContentValues();
 contentValues.put("blog_name", "Airsaid");
 contentValues.put("blog_link", "https://blog.csdn.net/airsaid");
 // line 為新添加的行號,出錯時返回 -1
 long line = mDatabase.insert("blog_info", null, contentValues);

delete

delete(String table, String whereClause, String[] whereArgs):
table:目標表名;
whereClause:滿足該條件的記錄會被刪除;
whereArgs:為 whereClause 傳入參數。

 int num = mDatabase.delete("blog_info", "blog_name like ?", new String[]{"Airsaid"});
 Toast.makeText(this, "一共刪除了:" + num + "條數據", Toast.LENGTH_SHORT).show();

update

update(String table, ContentValues values, String whereClause, String[] whereArgs):
table:目標表名;
values:想更新的數據;
whereClause:滿足條件的數據會被更新;
whereArgs:為 whereClause 傳入參數。

 ContentValues contentValues = new ContentValues();
 contentValues.put("blog_name", "周游");
 int num = mDatabase.update("blog_info", contentValues, "_id > ?", new String[]{"5"});

query

query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit):
distinct:是否去除重複記錄;
table:目標表名;
columns:要查詢的列名;
selection:查詢條件;
selectionArgs:占位符參數;
groupBy:分組;
having:對分組進行過濾/排序;
orderBy:排序;
limit:分頁。
由於查詢條件多變,query() 的參數實在偏長,寫查詢時不妨直接用 rawQuery()。

實例

下面做個例子:用戶分別輸入博客名和鏈接,點擊插入後存入數據庫,並用列表展示。

布局:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     xmlns:tools="https://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context="com.airsaid.sqlitedemo.MainActivity">
     <EditText
         android:id="@+id/edt_blog_name"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="10dp" />
     <EditText
         android:id="@+id/edt_blog_link"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="10dp" />
     <Button
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="10dp"
         android:onClick="insert"
         android:text="插入數據" />
     <ListView
         android:id="@+id/listView"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="10dp" />
 </LinearLayout>

代碼:

 public class MainActivity extends AppCompatActivity {
     private String mPath = Environment.getExternalStorageDirectory() + "/db/";
     private static final String DB_NAME = "blog.db";
     private EditText mEdtName;
     private EditText mEdtLink;
     private ListView mListView;
     private SQLiteDatabase mDatabase;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         mEdtName = (EditText) findViewById(R.id.edt_blog_name);
         mEdtLink = (EditText) findViewById(R.id.edt_blog_link);
         mListView = (ListView) findViewById(R.id.listView);
         File file = new File(mPath);
         if (!file.exists() && !file.isDirectory()) {
             file.mkdirs();
         }
         mDatabase = SQLiteDatabase.openOrCreateDatabase(mPath + DB_NAME, null);
         String createSql = "create table blog_info(_id integer primary key, blog_name varchar(255), blog_link varchar(255))";
         mDatabase.execSQL(createSql);
     }
     /** 插入數據 */
     public void insert(View v) {
         String name = mEdtName.getText().toString();
         String link = mEdtLink.getText().toString();
         mDatabase.execSQL("insert into blog_info values(null, ?, ?)", new String[]{name, link});
         Cursor cursor = mDatabase.rawQuery("select * from blog_info", null);
         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item_listview_blog, cursor, new String[]{"blog_name", "blog_link"}, new int[]{R.id.txt_name, R.id.txt_link}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
         mListView.setAdapter(adapter);
     }
 }

Item 布局:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_gravity="center"
     android:orientation="horizontal">
     <TextView
         android:id="@+id/txt_name"
         android:layout_width="0dp"
         android:layout_height="50dp"
         android:layout_weight="1" />
     <TextView
         android:id="@+id/txt_link"
         android:layout_width="0dp"
         android:layout_height="50dp"
         android:layout_weight="1" />
 </LinearLayout>

事務

數據庫操作離不開事務,SQLiteDatabase 提供了以下方法:
beginTransaction():開始事務;
endTransaction():結束事務;
inTransaction():判斷當前是否處於事務中。
調用 endTransaction() 時,究竟提交還是回滾,取決於是否調用了 setTransactionSuccessful() 設置事務標志——設置了且事務成功則提交,否則回滾。

SQLiteOpenHelper

真實項目中,很少直接用 SQLiteDatabase 打開數據庫,而是繼承 Android 提供的 SQLiteOpenHelper 抽象類。它是一個輔助類,用來幫助建立和管理數據庫。我們只需繼承它並實現兩個抽象方法:
onCreate(SQLiteDatabase db):初次生成數據庫時調用,用於創建表結構;
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):數據庫版本更新時調用。

方法

JAVA 方法 釋義 getWritableDatabase() 以寫方式打開數據庫
getReadableDatabase() 以讀寫方式打開數據庫
getDatabaseName() 返回數據庫名稱
onConfigure(SQLiteDatabase db) 配置數據庫連接時調用
onDowngrade(...) 數據庫降級時調用
onOpen(SQLiteDatabase db) 數據庫打開時調用
setWriteAheadLoggingEnabled(boolean) 啟用/禁用預寫日誌

實例

繼承 SQLiteOpenHelper,在 onCreate 中創建表:

 public class MyDatabaseHelper extends SQLiteOpenHelper {
     public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
         super(context, name, factory, version);
     }
     @Override
     public void onCreate(SQLiteDatabase db) {
         db.execSQL("create table dict(_id integer primary key autoincrement, word, detail)");
     }
     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
 }

布局分別為單詞輸入框和釋義輸入框,輸入後點擊保存,用戶再輸入要查詢的生詞,點擊查詢並以 Dialog 展示結果。添加生詞:

 public void add(View v) {
     String word = mEdtWord.getText().toString();
     String detail = mEdtDetail.getText().toString();
     if (TextUtils.isEmpty(word) || TextUtils.isEmpty(detail)) {
         Toast.makeText(this, "輸入的數據不能為空", Toast.LENGTH_SHORT).show();
         return;
     }
     SQLiteDatabase database = mDb.getReadableDatabase();
     database.execSQL("insert into dict values(null, ? , ?)", new String[]{word, detail});
     Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
 }

這裡通過 getReadableDatabase() 拿到 SQLiteDatabase 對象。需要注意的是:getReadableDatabase() 會先以讀寫方式打開,若磁盤空間已滿則打開失敗,再嘗試只讀方式;而 getWritableDatabase() 若磁盤空間已滿,打開時會直接出錯。

查詢:

 public void seek(View v) {
     String dict = mEdtInput.getText().toString();
     SQLiteDatabase database = mDb.getReadableDatabase();
     Cursor cursor = database.rawQuery("select * from dict where word like ? or detail like ?", new String[]{"%" + dict + "%", "%" + dict + "%"});
     List<String> dicts = new ArrayList<>();
     while (cursor.moveToNext()) {
         String word = cursor.getString(1);
         String detail = cursor.getString(2);
         dicts.add("生詞:" + word + " 解釋:" + detail);
     }
     showData(dicts);
 }

展示結果:

 private void showData(List<String> dicts) {
     if (dicts.size() < 1) {
         Toast.makeText(this, "沒有找到該生詞數據", Toast.LENGTH_SHORT).show();
         return;
     }
     new AlertDialog.Builder(this)
             .setTitle("查詢出來的單詞結果")
             .setItems(dicts.toArray(new String[dicts.size()]), new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     dialog.dismiss();
                 }
             }).create().show();
 }

運行結果:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved