將資料儲存在本機 SQLite.NET 資料庫中Store Data in a Local SQLite.NET Database

下載範例 下載範例Download Sample Download the sample

在本快速入門中,您將了解如何:In this quickstart, you will learn how to:

  • 使用 NuGet 套件管理員將 NuGet 套件新增至專案。Use the NuGet Package Manager to add a NuGet package to a project.
  • 將資料儲存在本機 SQLite.NET 資料庫。Store data locally in a SQLite.NET database.

快速入門會逐步說明如何將資料儲存在本機 SQLite.NET 資料庫中。The quickstart walks through how to store data in a local SQLite.NET database. 最終的應用程式如下所示:The final application is shown below:

必要條件Prerequisites

您應該先成功完成先前的快速入門,再嘗試本快速入門。You should successfully complete the previous quickstart before attempting this quickstart. 或者,下載先前的快速入門範例,並使用此範例作為本快速入門的起點。Alternatively, download the previous quickstart sample and use it as the starting point for this quickstart.

使用 Visual Studio 更新應用程式Update the app with Visual Studio

  1. 啟動 Visual Studio 並開啟 Notes 方案。Launch Visual Studio and open the Notes solution.

  2. 在 [方案總管] 中選取 Notes 專案,按一下滑鼠右鍵,然後選取 [管理 NuGet 套件] :In Solution Explorer, select the Notes project, right-click and select Manage NuGet Packages...:

  3. 在 [NuGet 套件管理員] 中選取 [瀏覽] 索引標籤,搜尋 sqlite-net-pcl NuGet 套件並加以選取,然後按一下 [安裝] 按鈕,將其新增至專案:In the NuGet Package Manager, select the Browse tab, search for the sqlite-net-pcl NuGet package, select it, and click the Install button to add it to the project:

    注意

    有許多名稱類似的 NuGet 套件。There are a number of NuGet packages with similar names. 正確的套件有下列屬性:The correct package has these attributes:

    • 作者: Frank A. KruegerAuthor(s): Frank A. Krueger
    • 識別碼: sqlite-net-pclId: sqlite-net-pcl
    • NuGet link: sqlite-net-pclNuGet link: sqlite-net-pcl

    不論套件名稱為何,此 NuGet 套件可用於 .NET Standard 專案。Despite the package name, this NuGet package can be used in .NET Standard projects.

    此套件會用來將資料庫作業併入應用程式。This package will be used to incorporate database operations into the application.

  4. 在 [方案總管] 的 Notes 專案中,開啟 Models 資料夾中的 Note.cs,並以下列程式碼取代現有程式碼:In Solution Explorer, in the Notes project, open Note.cs in the Models folder and replace the existing code with the following code:

    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 模型,以儲存應用程式中每個備註的相關資料。This class defines a Note model that will store data about each note in the application. ID 屬性會以 PrimaryKeyAutoIncrement 屬性標記,以確保 SQLite.NET 資料庫中每個 Note 執行個體都具有 SQLite.NET 提供的唯一識別碼。The ID property is marked with PrimaryKey and AutoIncrement attributes to ensure that each Note instance in the SQLite.NET database will have a unique id provided by SQLite.NET.

    按下 CTRL+S,將變更儲存到 Note.cs,然後關閉檔案。Save the changes to Note.cs by pressing CTRL+S, and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  5. 在 [方案總管] 中,將名為 Data 的新資料夾新增至 Notes 專案。In Solution Explorer, add a new folder named Data to the Notes project.

  6. 在 [方案總管] 的 Notes 專案中,將名為 NoteDatabase 的新類別新增到 Data 資料夾。In Solution Explorer, in the Notes project, add a new class named NoteDatabase to the Data folder.

  7. NoteDatabase.cs 中,以下列程式碼取代現有程式碼:In NoteDatabase.cs, replace the existing code with the following code:

    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()
            {
                return _database.Table<Note>().ToListAsync();
            }
    
            public Task<Note> GetNoteAsync(int id)
            {
                return _database.Table<Note>()
                                .Where(i => i.ID == id)
                                .FirstOrDefaultAsync();
            }
    
            public Task<int> SaveNoteAsync(Note note)
            {
                if (note.ID != 0)
                {
                    return _database.UpdateAsync(note);
                }
                else
                {
                    return _database.InsertAsync(note);
                }
            }
    
            public Task<int> DeleteNoteAsync(Note note)
            {
                return _database.DeleteAsync(note);
            }
        }
    }
    

    此類別包含的程式碼可建立資料庫、在資料庫中讀取和寫入資料,以及刪除資料庫的資料。This class contains code to create the database, read data from it, write data to it, and delete data from it. 此程式碼會使用非同步 SQLite.Net API,以將資料庫作業移至背景執行緒。The code uses asynchronous SQLite.NET APIs that move database operations to background threads. 此外,NoteDatabase 建構函式會採用資料庫檔案的路徑作為引數。In addition, the NoteDatabase constructor takes the path of the database file as an argument. 此路徑會由下一個步驟中的 App 類別提供。This path will be provided by the App class in the next step.

    按下 CTRL+S 以將變更儲存到 NoteDatabase.cs,然後關閉檔案。Save the changes to NoteDatabase.cs by pressing CTRL+S, and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  8. 在 [方案總管] 的 Notes 專案中,按兩下 App.xaml.cs 以開啟此檔案。In Solution Explorer, in the Notes project, double-click App.xaml.cs to open it. 將現有程式碼取代成下列程式碼:Then replace the existing code with the following code:

    using System;
    using System.IO;
    using Xamarin.Forms;
    using Notes.Data;
    
    namespace Notes
    {
        public partial class App : Application
        {
            static NoteDatabase database;
    
            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 NavigationPage(new NotesPage());
            }
    
            protected override void OnStart()
            {
                // Handle when your app starts
            }
    
            protected override void OnSleep()
            {
                // Handle when your app sleeps
            }
    
            protected override void OnResume()
            {
                // Handle when your app resumes
            }
        }
    }
    

    這段程式碼會定義 Database 屬性,其可建立新的 NoteDatabase 執行個體作為 singleton,將資料庫的檔案名稱當作引數傳入 NoteDatabase 建構函式。This code defines a Database property that creates a new NoteDatabase instance as a singleton, passing in the filename of the database as the argument to the NoteDatabase constructor. 將資料庫公開為唯一資料庫的優點為,所建立的單一資料庫連線會在應用程式執行時保持開啟,因此可避免每次執行資料庫作業時開啟和關閉資料庫檔案的費用。The advantage of exposing the database as a singleton is that a single database connection is created that's kept open while the application runs, therefore avoiding the expense of opening and closing the database file each time a database operation is performed.

    按下 CTRL+S 以將變更儲存到 App.xaml.cs,然後關閉檔案。Save the changes to App.xaml.cs by pressing CTRL+S, and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  9. 在 [方案總管] 的 Notes 專案中,按兩下 NotesPage.xaml.cs 以開啟此檔案。In Solution Explorer, in the Notes project, double-click NotesPage.xaml.cs to open it. 然後以下列程式碼取代 OnAppearing 方法:Then replace the OnAppearing method with the following code:

    protected override async void OnAppearing()
    {
        base.OnAppearing();
    
        listView.ItemsSource = await App.Database.GetNotesAsync();
    }
    

    此程式碼會將儲存在資料庫中的所有備註填入 ListViewThis code populates the ListView with any notes stored in the database.

    按下 CTRL+S 將變更儲存到 NotesPage.xaml.cs,然後關閉檔案。Save the changes to NotesPage.xaml.cs by pressing CTRL+S, and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  10. 在 [方案總管] 中,按兩下 NoteEntryPage.xaml.cs 以開啟此檔案。In Solution Explorer, double-click NoteEntryPage.xaml.cs to open it. 然後以下列程式碼取代 OnSaveButtonClickedOnDeleteButtonClicked 方法:Then replace the OnSaveButtonClicked and OnDeleteButtonClicked methods with the following code:

    async void OnSaveButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        note.Date = DateTime.UtcNow;
        await App.Database.SaveNoteAsync(note);
        await Navigation.PopAsync();
    }
    
    async void OnDeleteButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        await App.Database.DeleteNoteAsync(note);
        await Navigation.PopAsync();
    }
    

    NoteEntryPage 會在頁面的 BindingContext 中,儲存代表單一備註的 Note 執行個體。The NoteEntryPage stores a Note instance, which represents a single note, in the BindingContext of the page. 執行 OnSaveButtonClicked 事件處理常式,即會將 Note 執行個體儲存至資料庫,且應用程式會巡覽回上一頁。When the OnSaveButtonClicked event handler is executed, the Note instance is saved to the database and the application navigates back to the previous page. 執行 OnDeleteButtonClicked 事件處理常式,即會從資料庫刪除 Note 執行個體,且應用程式會巡覽回上一頁。When the OnDeleteButtonClicked event handler is executed, the Note instance is deleted from the database and the application navigates back to the previous page.

    按下 CTRL+S 將變更儲存到 NoteEntryPage.xaml.cs,然後關閉檔案。Save the changes to NoteEntryPage.xaml.cs by pressing CTRL+S, and close the file.

  11. 在每個平台上建置並執行專案。Build and run the project on each platform. 如需詳細資訊,請參閱建置快速入門For more information, see Building the quickstart.

    NotesPage 上按 + 按鈕,以巡覽至 NoteEntryPage 並輸入備註。On the NotesPage press the + button to navigate to the NoteEntryPage and enter a note. 儲存備註之後,應用程式會巡覽回 NotesPageAfter saving the note the application will navigate back to the NotesPage.

    輸入多個長短不一的備註,以觀察應用程式的行為。Enter a number of notes, of varying length, to observe the application behavior.

使用 Visual Studio for Mac 更新應用程式Update the app with Visual Studio for Mac

  1. 啟動 Visual Studio for Mac 並開啟 Notes 專案。Launch Visual Studio for Mac and open the Notes project.

  2. Solution Pad 中,選取 Notes 專案,按一下滑鼠右鍵,然後選取 [新增] > [新增 NuGet 套件] :In the Solution Pad, select the Notes project, right-click and select Add > Add NuGet Packages...:

  3. 在 [新增套件] 視窗中,搜尋 sqlite-net-pcl NuGet 套件並加以選取,然後按一下 [新增套件] 按鈕,將其新增至專案:In the Add Packages window, search for the sqlite-net-pcl NuGet package, select it, and click the Add Package button to add it to the project:

    注意

    有許多名稱類似的 NuGet 套件。There are a number of NuGet packages with similar names. 正確的套件有下列屬性:The correct package has these attributes:

    • 作者: Frank A. KruegerAuthor: Frank A. Krueger
    • 識別碼: sqlite-net-pclId: sqlite-net-pcl
    • NuGet link: sqlite-net-pclNuGet link: sqlite-net-pcl

    不論套件名稱為何,此 NuGet 套件可用於 .NET Standard 專案。Despite the package name, this NuGet package can be used in .NET Standard projects.

    此套件會用來將資料庫作業併入應用程式。This package will be used to incorporate database operations into the application.

  4. Solution PadNotes 專案中,開啟 Models 資料夾中的 Note.cs,並以下列程式碼取代現有程式碼:In the Solution Pad, in the Notes project, open Note.cs in the Models folder and replace the existing code with the following code:

    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 模型,以儲存應用程式中每個備註的相關資料。This class defines a Note model that will store data about each note in the application. ID 屬性會以 PrimaryKeyAutoIncrement 屬性標記,以確保 SQLite.NET 資料庫中每個 Note 執行個體都具有 SQLite.NET 提供的唯一識別碼。The ID property is marked with PrimaryKey and AutoIncrement attributes to ensure that each Note instance in the SQLite.NET database will have a unique id provided by SQLite.NET.

    選擇 [檔案] > [儲存] (或按下 ⌘ + S),將變更儲存到 Note.cs,然後關閉檔案。Save the changes to Note.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  5. Solution Pad 中,將名為 Data 的新資料夾新增至 Notes 專案。In the Solution Pad, add a new folder named Data to the Notes project.

  6. Solution PadNotes 專案中,將名為 NoteDatabase 的新類別新增到 Data 資料夾。In the Solution Pad, in the Notes project, add a new class named NoteDatabase to the Data folder.

  7. NoteDatabase.cs 中,以下列程式碼取代現有程式碼:In NoteDatabase.cs, replace the existing code with the following code:

    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()
            {
                return _database.Table<Note>().ToListAsync();
            }
    
            public Task<Note> GetNoteAsync(int id)
            {
                return _database.Table<Note>()
                                .Where(i => i.ID == id)
                                .FirstOrDefaultAsync();
            }
    
            public Task<int> SaveNoteAsync(Note note)
            {
                if (note.ID != 0)
                {
                    return _database.UpdateAsync(note);
                }
                else
                {
                    return _database.InsertAsync(note);
                }
            }
    
            public Task<int> DeleteNoteAsync(Note note)
            {
                return _database.DeleteAsync(note);
            }
        }
    }
    

    此類別包含的程式碼可建立資料庫、在資料庫中讀取和寫入資料,以及刪除資料庫的資料。This class contains code to create the database, read data from it, write data to it, and delete data from it. 此程式碼會使用非同步 SQLite.Net API,以將資料庫作業移至背景執行緒。The code uses asynchronous SQLite.NET APIs that move database operations to background threads. 此外,NoteDatabase 建構函式會採用資料庫檔案的路徑作為引數。In addition, the NoteDatabase constructor takes the path of the database file as an argument. 此路徑會由下一個步驟中的 App 類別提供。This path will be provided by the App class in the next step.

    選擇 [檔案] > [儲存] (或按下 ⌘ + S) 將變更儲存到 NoteDatabase.cs,然後關閉檔案。Save the changes to NoteDatabase.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  8. Solution PadNotes 專案中,按兩下 App.xaml.cs 以開啟此檔案。In the Solution Pad, in the Notes project, double-click App.xaml.cs to open it. 將現有程式碼取代成下列程式碼:Then replace the existing code with the following code:

    using System;
    using System.IO;
    using Xamarin.Forms;
    using Notes.Data;
    
    namespace Notes
    {
        public partial class App : Application
        {
            static NoteDatabase database;
    
            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 NavigationPage(new NotesPage());
            }
    
            protected override void OnStart()
            {
                // Handle when your app starts
            }
    
            protected override void OnSleep()
            {
                // Handle when your app sleeps
            }
    
            protected override void OnResume()
            {
                // Handle when your app resumes
            }
        }
    }
    

    這段程式碼會定義 Database 屬性,其可建立新的 NoteDatabase 執行個體作為 singleton,將資料庫的檔案名稱當作引數傳入 NoteDatabase 建構函式。This code defines a Database property that creates a new NoteDatabase instance as a singleton, passing in the filename of the database as the argument to the NoteDatabase constructor. 將資料庫公開為唯一資料庫的優點為,所建立的單一資料庫連線會在應用程式執行時保持開啟,因此可避免每次執行資料庫作業時開啟和關閉資料庫檔案的費用。The advantage of exposing the database as a singleton is that a single database connection is created that's kept open while the application runs, therefore avoiding the expense of opening and closing the database file each time a database operation is performed.

    選擇 [檔案] > [儲存] (或按下 ⌘ + S) 以將變更儲存到 App.xaml.cs,然後關閉檔案。Save the changes to App.xaml.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  9. Solution PadNotes 專案中,按兩下 NotesPage.xaml.cs 以開啟此檔案。In the Solution Pad, in the Notes project, double-click NotesPage.xaml.cs to open it. 然後以下列程式碼取代 OnAppearing 方法:Then replace the OnAppearing method with the following code:

    protected override async void OnAppearing()
    {
        base.OnAppearing();
    
        listView.ItemsSource = await App.Database.GetNotesAsync();
    }
    

    此程式碼會將儲存在資料庫中的所有備註填入 ListViewThis code populates the ListView with any notes stored in the database.

    選擇 [檔案] > [儲存] (或按下 ⌘ + S) 將變更儲存到 NotesPage.xaml.cs,然後關閉檔案。Save the changes to NotesPage.xaml.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

    警告

    此時若嘗試建置應用程式,將導致會在後續步驟中修正的錯誤。Attempting to build the application at this point will result in errors that will be fixed in subsequent steps.

  10. Solution Pad 中,按兩下 NoteEntryPage.xaml.cs 以開啟此檔案。In the Solution Pad, double-click NoteEntryPage.xaml.cs to open it. 然後以下列程式碼取代 OnSaveButtonClickedOnDeleteButtonClicked 方法:Then replace the OnSaveButtonClicked and OnDeleteButtonClicked methods with the following code:

    async void OnSaveButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        note.Date = DateTime.UtcNow;
        await App.Database.SaveNoteAsync(note);
        await Navigation.PopAsync();
    }
    
    async void OnDeleteButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        await App.Database.DeleteNoteAsync(note);
        await Navigation.PopAsync();
    }
    

    NoteEntryPage 會在頁面的 BindingContext 中,儲存代表單一備註的 Note 執行個體。The NoteEntryPage stores a Note instance, which represents a single note, in the BindingContext of the page. 執行 OnSaveButtonClicked 事件處理常式,即會將 Note 執行個體儲存至資料庫,且應用程式會巡覽回上一頁。When the OnSaveButtonClicked event handler is executed, the Note instance is saved to the database and the application navigates back to the previous page. 執行 OnDeleteButtonClicked 事件處理常式,即會從資料庫刪除 Note 執行個體,且應用程式會巡覽回上一頁。When the OnDeleteButtonClicked event handler is executed, the Note instance is deleted from the database and the application navigates back to the previous page.

    選擇 [檔案] > [儲存] (或按下 ⌘ + S) 將變更儲存到 NoteEntryPage.xaml.cs,然後關閉檔案。Save the changes to NoteEntryPage.xaml.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  11. 在每個平台上建置並執行專案。Build and run the project on each platform. 如需詳細資訊,請參閱建置快速入門For more information, see Building the quickstart.

    NotesPage 上按 + 按鈕,以巡覽至 NoteEntryPage 並輸入備註。On the NotesPage press the + button to navigate to the NoteEntryPage and enter a note. 儲存備註之後,應用程式會巡覽回 NotesPageAfter saving the note the application will navigate back to the NotesPage.

    輸入多個長短不一的備註,以觀察應用程式的行為。Enter a number of notes, of varying length, to observe the application behavior.

後續步驟Next steps

在本快速入門中,您已了解如何:In this quickstart, you learned how to:

  • 使用 NuGet 套件管理員將 NuGet 套件新增至專案。Use the NuGet Package Manager to add a NuGet package to a project.
  • 將資料儲存在本機 SQLite.NET 資料庫。Store data locally in a SQLite.NET database.

若要使用 XAML 樣式設定應用程式樣式,請繼續下一個快速入門。To style the application with XAML styles, continue to the next quickstart.