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

以SQLite.NET.Async-PCL異步存取SQLite資料庫( Xamarin.Android 實作)

編輯:關於 Android 開發

本文示範如何在 Xamarin.Android 專案中,透過 SQLite.NET.Async-PCL 以 async/await 的異步方式操作 SQLite 資料庫。相較於同步寫法,異步存取能有效避免阻塞 UI 執行緒,讓操作體驗更順暢。

一、簡介

本節重點在於「異步」兩個字:所有的建表、新增、查詢都透過 await 呼叫,讓資料庫操作在背景完成,UI 保持可互動。

二、執行成果

下圖左為初始頁面,右為點擊【建立資料庫】後的結果。

接著,左圖為點擊【新增單行】的結果,右圖為點擊【新增多行】的結果。

說明:為了聚焦於異步操作本身,本範例並未處理「重複學號」造成的衝突,而是直接把捕獲到的例外顯示出來。這樣做只是為了讓程式碼保持精簡;在真實專案中,你應該對例外做更嚴謹的處理,否則很容易出問題。

三、主要設計步驟

1. 加入 SQLite.NET.Async-PCL 套件

在專案的【參考】上按右鍵,選擇【管理 NuGet 套件】,資料來源挑選 NuGet 官方來源,於搜尋框輸入 sqlite,找到 SQLite.NET.Async-PCL,選取最新版本(本範例使用 3.1.1),按下安裝。安裝完成後,Visual Studio 會自動為你加入 SQLite.Net.Async 的參考。

2. 建立資料庫與資料表

在 SrcDemos 資料夾下新增 MyDb4Model 資料夾,用來存放與 MyDb4.db 相關的 .cs 檔。

(1)Student.cs —— 定義資料表對應的模型:

using System;
using SQLite.Net.Attributes;

namespace MyDemos.SrcDemos.MyDb4Model
{
    [Table("Student")]
    public class Student
    {
        [PrimaryKey, AutoIncrement]
        public int id { get; set; }
        [Unique, NotNull]
        public string XueHao { get; set; }
        [MaxLength(30), NotNull]
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }

        public override string ToString()
        {
            return string.Format("[學號={0}, 姓名={1}, 出生日期={2:yyyy-MM-dd}]\n",
                XueHao, Name, BirthDate);
        }
    }
}

(2)MyDb4.cs —— 封裝異步連線:

using System;
using System.IO;
using SQLite.Net;
using SQLite.Net.Async;
using SQLite.Net.Platform.XamarinAndroid;

namespace MyDemos.SrcDemos.MyDb4Model
{
    public static class MyDb4
    {
        private static readonly string dbPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb4.db");

        public static SQLiteAsyncConnection GetAsyncConnection()
        {
            SQLitePlatformAndroid platform = new SQLitePlatformAndroid();
            SQLiteConnectionString connStr = new SQLiteConnectionString(dbPath, false);
            return new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(platform, connStr));
        }
    }
}

3. 新增 ch1304_Main.axml 版面

版面由上而下分為三區塊:上方一列按鈕(建立資料庫、新增單行、新增多行),中間是結果顯示的 TextView,下方留白。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <LinearLayout android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".2" android:gravity="center">
        <Button android:text="建立資料庫" android:id="@+id/btnCreateDB" ... />
        <Button android:text="新增單行" android:id="@+id/btnCreateSingle" ... />
        <Button android:text="新增多行" android:id="@+id/btnCreateList" ... />
    </LinearLayout>
    <LinearLayout android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.6">
        <TextView android:text="結果" android:id="@+id/textView1" ... />
        <TextView android:id="@+id/txtResults" ... />
    </LinearLayout>
</LinearLayout>

4. 新增 ch1304MainActivity.cs

Activity 中為三顆按鈕掛上 async 事件處理器,分別示範建表、單筆新增與批次新增,並在操作後呼叫 GetStudents() 取得目前資料。

using System;
using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Widget;
using MyDemos.SrcDemos.MyDb4Model;
using SQLite.Net;
using System.Threading.Tasks;

namespace MyDemos.SrcDemos
{
    [Activity(Label = "【例13-4】SQLite基本用法4")]
    public class ch1304MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ch1304_Main);
            var btnCreate = FindViewById<Button>(Resource.Id.btnCreateDB);
            var btnSingle = FindViewById<Button>(Resource.Id.btnCreateSingle);
            var btnList = FindViewById<Button>(Resource.Id.btnCreateList);
            var txtResult = FindViewById<TextView>(Resource.Id.txtResults);

            // 資料庫建立前先停用相關按鈕
            btnSingle.Enabled = btnList.Enabled = false;

            btnCreate.Click += async delegate {
                try {
                    var conn = MyDb4.GetAsyncConnection();
                    await conn.CreateTableAsync<Student>();
                    await conn.DeleteAllAsync<Student>();
                    txtResult.Text = "建立成功。";
                    btnList.Enabled = btnSingle.Enabled = true;
                } catch (SQLiteException ex) {
                    txtResult.Text = "建立失敗:" + ex.Message;
                }
            };

            btnSingle.Click += async delegate {
                var student = new Student { XueHao = "01001", Name = "張三", BirthDate = new DateTime(1995, 4, 7) };
                try {
                    var conn = MyDb4.GetAsyncConnection();
                    int x = await conn.InsertAsync(student);
                    await conn.UpdateAsync(student);
                    txtResult.Text = $"新增了 {x} 筆記錄。\n" + await GetStudents();
                } catch (SQLiteException ex) {
                    txtResult.Text = "Error:" + ex.Message;
                }
            };

            btnList.Click += async delegate {
                var list = new List<Student>{
                    new Student { XueHao="01002", Name="李四", BirthDate=new DateTime(1995,4,8) },
                    new Student { XueHao="01003", Name="王五", BirthDate=new DateTime(1995,4,9) },
                    new Student { XueHao="01004", Name="趙六", BirthDate=new DateTime(1995,4,10) }
                };
                try {
                    var conn = MyDb4.GetAsyncConnection();
                    int x = await conn.InsertAllAsync(list);
                    await conn.UpdateAllAsync(list);
                    txtResult.Text = $"新增了 {x} 筆記錄。\n" + await GetStudents();
                } catch (SQLiteException ex) {
                    txtResult.Text = "Error:" + ex.Message;
                }
            };
        }

        private static async Task<string> GetStudents()
        {
            var conn = MyDb4.GetAsyncConnection();
            int count = await conn.Table<Student>().CountAsync();
            string s = $"目前記錄數:{count}\n";
            var data = await conn.Table<Student>().ToListAsync();
            foreach (var v in data) s += v.ToString();
            return s;
        }
    }
}

透過以上步驟,你就能在 Xamarin.Android 中以 async/await 優雅地完成 SQLite 的建表、新增與查詢,並把結果即時回顯到介面上。

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