將資料儲存在本機 SQLite.NET 資料庫中

Download Sample 下載範例

在本快速入門中,您將了解如何:

  • 將資料儲存在本機 SQLite.NET 資料庫。

本快速入門會逐步解說如何從 Xamarin.Forms Shell應用程式將資料儲存在本機 SQLite.NET 資料庫中。 最終的應用程式如下所示:

Notes PageNote Entry Page

必要條件

您應該先成功完成先前的快速入門,再嘗試本快速入門。 或者,下載先前的快速入門範例,並使用此範例作為本快速入門的起點。

使用 Visual Studio 更新應用程式

  1. 啟動 Visual Studio 並開啟 Notes 方案。

  2. 方案總管 中,以滑鼠右鍵按兩下 [附註] 解決方案,然後選取 [管理方案的 NuGet 套件...]:

    Manage NuGet Packages

  3. NuGet 封裝管理員 中,選取 [流覽] 索引卷標,然後搜尋 sqlite-net-pcl NuGet 套件。

    警告

    有許多具有類似名稱的 NuGet 套件。 正確的套件有下列屬性:

    不論套件名稱為何,此 NuGet 套件可用於 .NET Standard 專案。

    NuGet 封裝管理員 中,選取正確的 sqlite-net-pcl 套件、核取 [專案] 複選框,然後按兩下 [安裝] 按鈕將它新增至解決方案:

    Select sqlite-net-pcl

    此套件將用來將資料庫作業併入應用程式,並將新增至解決方案中的每個專案。

    重要

    SQLite.NET 是 praeclarum/sqlite-net 存放庫所支援的第三方連結庫。

    關閉 [NuGet 套件管理員]

  4. 在 [方案總管]Notes 專案中,開啟 Models 資料夾中的 Note.cs,並以下列程式碼取代現有程式碼:

    using System;
    using SQLite;
    
    namespace Notes.Models
    {
        public class Note
        {
            [PrimaryKey, AutoIncrement]
            public int ID { get; set; }
            public string Text { get; set; }
            public DateTime Date { get; set; }
        }
    }
    

    此類別會定義 Note 模型,以儲存應用程式中每個備註的相關資料。 ID 屬性會以 PrimaryKeyAutoIncrement 屬性標記,以確保 SQLite.NET 資料庫中每個 Note 執行個體都具有 SQLite.NET 提供的唯一識別碼。

    CTRL+S 將變更儲存至Note.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  5. 在 [方案總管] 中,將名為 Data 的新資料夾新增至 Notes 專案。

  6. 在 [方案總管]Notes 專案中,將名為 NoteDatabase 的新類別新增到 Data 資料夾。

  7. NoteDatabase.cs 中,以下列程式碼取代現有程式碼:

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using SQLite;
    using Notes.Models;
    
    namespace Notes.Data
    {
        public class NoteDatabase
        {
            readonly SQLiteAsyncConnection database;
    
            public NoteDatabase(string dbPath)
            {
                database = new SQLiteAsyncConnection(dbPath);
                database.CreateTableAsync<Note>().Wait();
            }
    
            public Task<List<Note>> GetNotesAsync()
            {
                //Get all notes.
                return database.Table<Note>().ToListAsync();
            }
    
            public Task<Note> GetNoteAsync(int id)
            {
                // Get a specific note.
                return database.Table<Note>()
                                .Where(i => i.ID == id)
                                .FirstOrDefaultAsync();
            }
    
            public Task<int> SaveNoteAsync(Note note)
            {
                if (note.ID != 0)
                {
                    // Update an existing note.
                    return database.UpdateAsync(note);
                }
                else
                {
                    // Save a new note.
                    return database.InsertAsync(note);
                }
            }
    
            public Task<int> DeleteNoteAsync(Note note)
            {
                // Delete a note.
                return database.DeleteAsync(note);
            }
        }
    }
    

    此類別包含的程式碼可建立資料庫、在資料庫中讀取和寫入資料,以及刪除資料庫的資料。 此程式碼會使用非同步 SQLite.Net API,以將資料庫作業移至背景執行緒。 此外,NoteDatabase 建構函式會採用資料庫檔案的路徑作為引數。 此路徑會由下一個步驟中的 App 類別提供。

    CTRL+S 將變更儲存至NoteDatabase.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  8. 方案總管Notes 專案中,展開 [App.xaml],然後按兩下 [App.xaml.cs 以開啟它。 將現有程式碼取代成下列程式碼:

    using System;
    using System.IO;
    using Notes.Data;
    using Xamarin.Forms;
    
    namespace Notes
    {
        public partial class App : Application
        {
            static NoteDatabase database;
    
            // Create the database connection as a singleton.
            public static NoteDatabase Database
            {
                get
                {
                    if (database == null)
                    {
                        database = new NoteDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Notes.db3"));
                    }
                    return database;
                }
            }
    
            public App()
            {
                InitializeComponent();
                MainPage = new AppShell();
            }
    
            protected override void OnStart()
            {
            }
    
            protected override void OnSleep()
            {
            }
    
            protected override void OnResume()
            {
            }
        }
    }
    

    這段程式碼會定義 Database 屬性,其可建立新的 NoteDatabase 執行個體作為 singleton,將資料庫的檔案名稱當作引數傳入 NoteDatabase 建構函式。 將資料庫公開為唯一資料庫的優點為,所建立的單一資料庫連線會在應用程式執行時保持開啟,因此可避免每次執行資料庫作業時開啟和關閉資料庫檔案的費用。

    CTRL+S 將變更儲存至App.xaml.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  9. 方案總管 的 Notes 專案中,展開 Views 資料夾中的 NotesPage.xaml,然後開啟 NotesPage.xaml.cs 然後以下列程式碼取代 OnAppearingOnSelectionChanged 方法:

    protected override async void OnAppearing()
    {
        base.OnAppearing();
    
        // Retrieve all the notes from the database, and set them as the
        // data source for the CollectionView.
        collectionView.ItemsSource = await App.Database.GetNotesAsync();
    }
    
    async void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.CurrentSelection != null)
        {
            // Navigate to the NoteEntryPage, passing the ID as a query parameter.
            Note note = (Note)e.CurrentSelection.FirstOrDefault();
            await Shell.Current.GoToAsync($"{nameof(NoteEntryPage)}?{nameof(NoteEntryPage.ItemId)}={note.ID.ToString()}");
        }
    }    
    

    方法會儲存OnAppearingCollectionView在資料庫中的任何附註填入 。 方法 OnSelectionChanged 會巡覽至 NoteEntryPage,將 ID 所選 Note 物件的 屬性當做查詢參數傳遞。

    CTRL+S 將變更儲存至NotesPage.xaml.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  10. 方案總管 中,展開 Views 資料夾中的 NoteEntryPage.xaml,然後開啟 NoteEntryPage.xaml.cs。 然後使用下列程式代碼取代 LoadNoteOnSaveButtonClickedOnDeleteButtonClicked 方法:

    async void LoadNote(string itemId)
    {
        try
        {
            int id = Convert.ToInt32(itemId);
            // Retrieve the note and set it as the BindingContext of the page.
            Note note = await App.Database.GetNoteAsync(id);
            BindingContext = note;
        }
        catch (Exception)
        {
            Console.WriteLine("Failed to load note.");
        }
    }
    
    async void OnSaveButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        note.Date = DateTime.UtcNow;
        if (!string.IsNullOrWhiteSpace(note.Text))
        {
            await App.Database.SaveNoteAsync(note);
        }
    
        // Navigate backwards
        await Shell.Current.GoToAsync("..");
    }
    
    async void OnDeleteButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        await App.Database.DeleteNoteAsync(note);
    
        // Navigate backwards
        await Shell.Current.GoToAsync("..");
    }
    

    NoteEntryPage 使用 LoadNote 方法,從資料庫擷取附注,其標識碼會當做查詢參數傳遞至頁面,並將它儲存為 Note 頁面的物件 BindingContext 。 執行 OnSaveButtonClicked 事件處理常式,即會將 Note 執行個體儲存至資料庫,且應用程式會巡覽回上一頁。 執行 OnDeleteButtonClicked 事件處理常式,即會從資料庫刪除 Note 執行個體,且應用程式會巡覽回上一頁。

    CTRL+S 將變更儲存至NoteEntryPage.xaml.cs

  11. 在每個平台上建置並執行專案。 如需詳細資訊,請參閱建置快速入門

    NotesPage,按下 [新增 ] 按鈕以流覽至 NoteEntryPage 並輸入附注。 儲存備註之後,應用程式會巡覽回 NotesPage

    輸入數個不同長度的附注來觀察應用程式行為。 關閉應用程式,然後重新啟動它,以確保您輸入的筆記已儲存至資料庫。

使用 Visual Studio for Mac 更新應用程式

  1. 啟動 Visual Studio for Mac 並開啟 Notes 方案。

  2. 在 Solution Pad 中,以滑鼠右鍵按兩下 [附註] 解決方案,然後選取 [管理 NuGet 套件...]:

    Manage NuGet Packages

  3. 在 [ 管理 NuGet 套件 ] 對話框中,選取 [ 瀏覽 ] 索引標籤,然後搜尋 sqlite-net-pcl NuGet 套件。

    警告

    有許多具有類似名稱的 NuGet 套件。 正確的套件有下列屬性:

    不論套件名稱為何,此 NuGet 套件可用於 .NET Standard 專案。

    在 [ 管理 NuGet 套件 ] 對話框中,選取 sqlite-net-pcl 套件,然後按兩下 [新增套件 ] 按鈕將它新增至解決方案:

    Select sqlite-net-pcl

    此套件會用來將資料庫作業併入應用程式。

  4. 在 [ 選取專案 ] 對話框中,確定已核取每個複選框,然後按 [ 確定 ] 按鈕:

    Add Package to All Projects

    這會將 NuGet 套件新增至方案中的每個專案。

  5. Solution PadNotes 專案中,開啟 Models 資料夾中的 Note.cs,並以下列程式碼取代現有程式碼:

    using System;
    using SQLite;
    
    namespace Notes.Models
    {
        public class Note
        {
            [PrimaryKey, AutoIncrement]
            public int ID { get; set; }
            public string Text { get; set; }
            public DateTime Date { get; set; }
        }
    }
    

    此類別會定義 Note 模型,以儲存應用程式中每個備註的相關資料。 ID 屬性會以 PrimaryKeyAutoIncrement 屬性標記,以確保 SQLite.NET 資料庫中每個 Note 執行個體都具有 SQLite.NET 提供的唯一識別碼。

    選擇 [檔案>儲存],或按 ⌘ + S,將變更儲存至Note.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  6. Solution Pad 中,將名為 Data 的新資料夾新增至 Notes 專案。

  7. Solution PadNotes 專案中,將名為 NoteDatabase 的新類別新增到 Data 資料夾。

  8. NoteDatabase.cs 中,以下列程式碼取代現有程式碼:

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using SQLite;
    using Notes.Models;
    
    namespace Notes.Data
    {
        public class NoteDatabase
        {
            readonly SQLiteAsyncConnection database;
    
            public NoteDatabase(string dbPath)
            {
                database = new SQLiteAsyncConnection(dbPath);
                database.CreateTableAsync<Note>().Wait();
            }
    
            public Task<List<Note>> GetNotesAsync()
            {
                //Get all notes.
                return database.Table<Note>().ToListAsync();
            }
    
            public Task<Note> GetNoteAsync(int id)
            {
                // Get a specific note.
                return database.Table<Note>()
                                .Where(i => i.ID == id)
                                .FirstOrDefaultAsync();
            }
    
            public Task<int> SaveNoteAsync(Note note)
            {
                if (note.ID != 0)
                {
                    // Update an existing note.
                    return database.UpdateAsync(note);
                }
                else
                {
                    // Save a new note.
                    return database.InsertAsync(note);
                }
            }
    
            public Task<int> DeleteNoteAsync(Note note)
            {
                // Delete a note.
                return database.DeleteAsync(note);
            }
        }
    }
    

    此類別包含的程式碼可建立資料庫、在資料庫中讀取和寫入資料,以及刪除資料庫的資料。 此程式碼會使用非同步 SQLite.Net API,以將資料庫作業移至背景執行緒。 此外,NoteDatabase 建構函式會採用資料庫檔案的路徑作為引數。 此路徑會由下一個步驟中的 App 類別提供。

    選擇 [檔案>儲存] 或按 ⌘ + S,將變更儲存至NoteDatabase.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  9. 在 Solution Pad 的 Notes 專案中,展開 App.xaml,然後按兩下App.xaml.cs加以開啟。 將現有程式碼取代成下列程式碼:

    using System;
    using System.IO;
    using Notes.Data;
    using Xamarin.Forms;
    
    namespace Notes
    {
        public partial class App : Application
        {
            static NoteDatabase database;
    
            // Create the database connection as a singleton.
            public static NoteDatabase Database
            {
                get
                {
                    if (database == null)
                    {
                        database = new NoteDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Notes.db3"));
                    }
                    return database;
                }
            }
    
            public App()
            {
                InitializeComponent();
                MainPage = new AppShell();
            }
    
            protected override void OnStart()
            {
            }
    
            protected override void OnSleep()
            {
            }
    
            protected override void OnResume()
            {
            }
        }
    }
    

    這段程式碼會定義 Database 屬性,其可建立新的 NoteDatabase 執行個體作為 singleton,將資料庫的檔案名稱當作引數傳入 NoteDatabase 建構函式。 將資料庫公開為唯一資料庫的優點為,所建立的單一資料庫連線會在應用程式執行時保持開啟,因此可避免每次執行資料庫作業時開啟和關閉資料庫檔案的費用。

    選擇 [檔案>儲存] 來儲存App.xaml.cs的變更(或按 ⌘ + S)。

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  10. 在 Solution Pad 的 Notes 專案中,展開 Views 資料夾中的 NotesPage.xaml,然後開啟 NotesPage.xaml.cs。 然後以下列程式碼取代 OnAppearingOnSelectionChanged 方法:

    protected override async void OnAppearing()
    {
        base.OnAppearing();
    
        // Retrieve all the notes from the database, and set them as the
        // data source for the CollectionView.
        collectionView.ItemsSource = await App.Database.GetNotesAsync();
    }
    
    async void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.CurrentSelection != null)
        {
            // Navigate to the NoteEntryPage, passing the ID as a query parameter.
            Note note = (Note)e.CurrentSelection.FirstOrDefault();
            await Shell.Current.GoToAsync($"{nameof(NoteEntryPage)}?{nameof(NoteEntryPage.ItemId)}={note.ID.ToString()}");
        }
    }    
    

    方法會儲存OnAppearingCollectionView在資料庫中的任何附註填入 。 方法 OnSelectionChanged 會巡覽至 NoteEntryPage,將 ID 所選 Note 物件的 屬性當做查詢參數傳遞。

    選擇 [檔案>儲存] 來儲存變更至NotesPage.xaml.cs (或按 ⌘ + S)。

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  11. 在 Solution Pad 中,展開 Views 資料夾中的 NoteEntryPage.xaml,然後開啟 NoteEntryPage.xaml.cs 然後使用下列程式代碼取代 LoadNoteOnSaveButtonClickedOnDeleteButtonClicked 方法:

    async void LoadNote(string itemId)
    {
        try
        {
            int id = Convert.ToInt32(itemId);
            // Retrieve the note and set it as the BindingContext of the page.
            Note note = await App.Database.GetNoteAsync(id);
            BindingContext = note;
        }
        catch (Exception)
        {
            Console.WriteLine("Failed to load note.");
        }
    }
    
    async void OnSaveButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        note.Date = DateTime.UtcNow;
        if (!string.IsNullOrWhiteSpace(note.Text))
        {
            await App.Database.SaveNoteAsync(note);
        }
    
        // Navigate backwards
        await Shell.Current.GoToAsync("..");
    }
    
    async void OnDeleteButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        await App.Database.DeleteNoteAsync(note);
    
        // Navigate backwards
        await Shell.Current.GoToAsync("..");
    }
    

    NoteEntryPage 使用 LoadNote 方法,從資料庫擷取附注,其標識碼會當做查詢參數傳遞至頁面,並將它儲存為 Note 頁面的物件 BindingContext 。 執行 OnSaveButtonClicked 事件處理常式,即會將 Note 執行個體儲存至資料庫,且應用程式會巡覽回上一頁。 執行 OnDeleteButtonClicked 事件處理常式,即會從資料庫刪除 Note 執行個體,且應用程式會巡覽回上一頁。

    選擇 [檔案>儲存],或按 ⌘ + S,將變更儲存至NoteEntryPage.xaml.cs

  12. 在每個平台上建置並執行專案。 如需詳細資訊,請參閱建置快速入門

    NotesPage,按下 [新增 ] 按鈕以流覽至 NoteEntryPage 並輸入附注。 儲存備註之後,應用程式會巡覽回 NotesPage

    輸入數個不同長度的附注來觀察應用程式行為。 關閉應用程式,然後重新啟動它,以確保您輸入的筆記已儲存至資料庫。

下一步

在本快速入門中,您已了解如何:

  • 將資料儲存在本機 SQLite.NET 資料庫。

繼續進行下一個快速入門,以 XAML 樣式設定應用程式樣式。