uwp连接mysql数据库_在 UWP 应用中使用 SQLite 数据库

在 UWP 应用中使用 SQLite 数据库Use a SQLite database in a UWP app

06/26/2020

本文内容

可以使用 SQLite 在用户设备上的轻量级数据库中存储和检索数据。You can use SQLite to store and retrieve data in a light-weight database on the user's device. 本指南演示如何执行该操作。This guide shows you how.

使用 SQLite 进行本地存储一些好处Some benefits of using SQLite for local storage

✔️SQLite 具有轻量和独立的特点。SQLite is light-weight and self-contained. 它是没有其他任何依赖项的代码库。It's a code library without any other dependencies. 无需进行任何配置。There's nothing to configure.

✔️没有数据库服务器。There's no database server. 客户端和服务器在同一进程中运行。The client and the server run in the same process.

✔️SQLite 位于公共域中,因此你可以自由地使用它并将它与应用一起分配。SQLite is in the public domain so you can freely use and distribute it with your app.

✔️SQLite 可跨平台和体系结构工作。SQLite works across platforms and architectures.

可在此处了解有关 SQLite 的详细信息。You can read more about SQLite here.

选择抽象层Choose an abstraction layer

我们建议使用由 Microsoft 构建的 Entity Framework Core 或开源 SQLite 库。We recommend that you use either the Entity Framework Core or the open-source SQLite library built by Microsoft.

Entity Framework CoreEntity Framework Core

Entity Framework (EF) 是一个对象关系映射程序,可用于使用特定于域的对象处理关系数据。Entity Framework (EF) is an object-relational mapper that you can use to work with relational data by using domain-specific objects. 如果已使用此框架处理其他 .NET 应用中的数据,则可以将该代码迁移到 UWP 应用,它将处理对连接字符串的相应更改。If you've already used this framework to work with data in other .NET apps, you can migrate that code to a UWP app and it will work with appropriate changes to the connection string.

SQLite 库SQLite library

The Microsoft.Data.Sqlite library implements the interfaces in the System.Data.Common namespace. Microsoft 将主动保留这些实现,它们提供了围绕低级别本机 SQLite API 的直观的包装器。Microsoft actively maintains these implementations, and they provide an intuitive wrapper around the low-level native SQLite API.

本指南的其余部分将帮助你使用此库。The rest of this guide helps you to use this library.

将解决方案设置为使用 Microsoft.Data.SQlite 库Set up your solution to use the Microsoft.Data.SQlite library

我们将从基本 UWP 项目入手,添加类库,然后安装合适的 Nuget 包。We'll start with a basic UWP project, add a class library, and then install the appropriate Nuget packages.

添加到解决方案的类库的类型以及安装的特定程序包取决于应用面向的最低版本的 Windows SDK。The type of class library that you add to your solution, and the specific packages that you install depends on the minimum version of the Windows SDK that your app targets. 可以在 UWP 项目的属性页中找到该信息。You can find that information in the properties page of your UWP project.

aa11b4b03c585edb2fcdb81e83eb196f.png

根据 UWP 项目面向的最低版本的 Windows SDK,使用以下章节之一。Use one of the following sections depending on the minimum version of the Windows SDK that your UWP project targets.

项目的最低版本没有将 Fall Creators Update 作为目标The minimum version of your project does not target the Fall Creators Update

如果使用的是 Visual Studio 2015,请单击“帮助”->“关于 Microsoft Visual Studio”。If you're using Visual Studio 2015, click Help->About Microsoft Visual Studio. 然后,在已安装程序的列表中,确保你具有 NuGet 包管理器版本 3.5 或更高版本。Then in the list of installed programs, make sure that you have NuGet package manager version of 3.5 or higher. 如果版本号较低,请安装此处提供的更高版本的 NuGet。If your version number is lower than that, install a later version of NuGet here. 在该页面上,你将发现所有版本的 Nuget 都在 Visual Studio 2015 标题下方列出。On that page, you'll find all of the versions of Nuget listed beneath the Visual Studio 2015 heading.

接下来,将类库添加到解决方案。Next, add class library to your solution. 你不必使用类库来包含你的数据访问代码,但我们会使用一个我们的示例。You don't have to use a class library to contain your data access code, but we'll use one our example. 我们将库命名为 DataAccessLibrary,并将库中的类命名为 DataAccess。We'll name the library DataAccessLibrary and we'll name the class in the library to DataAccess.

c6cb361ce1e7cf28cb82eece289e78aa.png

右键单击该解决方法,然后单击“管理解决方案的 NuGet 包”。Right-click the solution, and then click Manage NuGet Packages for Solution.

aac30db9a811ec7ba1ef3b76361f5b82.png

如果使用的是 Visual Studio 2015,请选择“已安装”选项卡,并确保 Microsoft.NETCore.UniversalWindowsPlatform 程序包的版本号为 5.2.2 或更高。If you're using Visual Studio 2015, Choose the Installed tab, and make sure that the version number of the Microsoft.NETCore.UniversalWindowsPlatform package is 5.2.2 or higher.

e99df59c688c317a9b14766935ab3e3b.png

如果不是,请将包更新到更新的版本。If it isn't, update the package to a newer version.

选择“浏览”选项卡,然后搜索“Microsoft.Data.SQLite”程序包。Choose the Browse tab, and search for the Microsoft.Data.SQLite package. 安装该程序包的版本 1.1.1(或更低)。Install version 1.1.1 (or lower) of that package.

82306b366d65aac03b935c1c4c42066a.png

你最低版本的项目已锁定 Fall Creators UpdateThe minimum version of your project targets the Fall Creators Update

将 UWP 项目的最低版本升级到 Fall Creators Update 有几个好处。There's a couple of benefits to raising the minimum version of your UWP project to the Fall Creators update.

首先,你可以使用 .NET Standard 2.0 库而不是常规的类库。First off, you can use .NET Standard 2.0 libraries instead of regular class libraries. 这意味着你可以将数据访问代码与任何其他基于 .NET 的应用(如 WPF、Windows 窗体、Android、iOS 或 ASP.NET 应用)共享。That means that you can share your data access code with any other .NET-based app such as a WPF, Windows Forms, Android, iOS, or ASP.NET app.

其次,应用不需将 SQLite 库打包。Secondly, your app does not have to package SQLite libraries. 相反,应用可以使用随 Windows 一起安装的 SQLite 版本。Instead, your app can use the version of SQLite that comes installed with Windows. 这将带来几个方面的好处。This helps you in a few ways.

✔️减小了应用程序的大小,因为你不必下载 SQLite 二进制文件然后将其打包为应用程序的一部分。Reduces the size of your application because you don't have to download the SQLite binary, and then package it as part of your application.

✔️如果 SQLite 发布了针对 SQLite 中的 bug 和安全漏洞的重要修复程序,你就不必向用户推送你的应用的新版本。Prevents you from having to push a new version of your app to users in the event that SQLite publishes critical fixes to bugs and security vulnerabilities in SQLite. Windows 版本的 SQLite 由 Microsoft 与 SQLite.org 协作维护。The Windows version of SQLite is maintained by Microsoft in coordination with SQLite.org.

✔️应用加载时间可能更短,因为 SDK 版本的 SQLite 很有可能已被加载到内存中。App load time has the potential to be faster because most likely, the SDK version of SQLite will already be loaded into memory.

让我们开始向你的解决方案添加 .NET Standard 2.0 类库。Lets start by adding a .NET Standard 2.0 class library to your solution. 你不必使用类库来包含你的数据访问代码,但我们会使用一个我们的示例。It's not necessary that you use a class library to contain your data access code, but we'll use one our example. 我们将库命名为 DataAccessLibrary,并将库中的类命名为 DataAccess。We'll name the library DataAccessLibrary and we'll name the class in the library to DataAccess.

34eec2ea0e16892f66596fbb272fa8d4.png

右键单击该解决方法,然后单击“管理解决方案的 NuGet 包”。Right-click the solution, and then click Manage NuGet Packages for Solution.

4a13f38b316d5632fe669cb6eae60ca4.png

备注

如果希望 .NET Standard 类库能够访问 UWP 应用的应用文件夹和图像资产,则需要将其标记为其属性中的 EmbeddedResource 和 CopyAlways 。If you want your .NET Standard class library to be able to access app folders and image assets of your UWP app, you will need to mark it as EmbeddedResource and CopyAlways in its properties.

此时,你已经有一个选择。At this point, you have a choice. 你可以使用 Windows 附带的 SQLite 版本,如果你出于某种原因要使用特定版本的 SQLite,则可以在程序中包含 SQLite 库。You can use the version of SQLite that is included with Windows or if you have some reason to use a specific version of SQLite, you can include the SQLite library in your package.

让我们开始演示如何使用 Windows 附带的 SQLite 版本。Let's start with how you use the version of SQLite that included with Windows.

使用随 Windows 一起安装的 SQLite 版本To use the version of SQLite that is installed with Windows

选择“浏览”选项卡,搜索“Microsoft.Data.SQLite.core”程序包,然后安装它。Choose the Browse tab, and search for the Microsoft.Data.SQLite.core package, and then install it.

0e8d297a9ccaa24cff4ae809494fd59a.png

搜索“SQLitePCLRaw.bundle_winsqlite3”程序包,然后仅将它安装到应用程序中的 UWP 项目。Search for the SQLitePCLRaw.bundle_winsqlite3 package, and then install it only to the UWP project in your solution.

255667db5f3e9a1a13f744bb6473dc52.png

将 SQLite 包含在你的应用中To include SQLite with your app

你不必执行此操作。You don't have to do this. 但如果你出于某种原因要将特定版本的 SQLite 包含在你的应用中,请选择“浏览”选项卡,然后搜索“Microsoft.Data.SQLite”程序包。But if you have a reason to include a specific version of SQLite with your app, choose the Browse tab, and search for the Microsoft.Data.SQLite package. 安装该程序包的版本 2.0(或更低)。Install version 2.0 (or lower) of that package.

0289d3116b18669f6219543409a8a2ab.png

在 SQLite 数据库中添加和检索数据Add and retrieve data in a SQLite database

我们将执行以下操作:We'll do these things:

1️⃣准备数据访问类。Prepare the data access class.

2️⃣初始化 SQLite 数据库。Initialize the SQLite database.

3️⃣将数据插入到 SQLite 数据库。Insert data into the SQLite database.

4️⃣从 SQLite 数据库检索数据。Retrieve data from the SQLite database.

5️⃣添加基本用户界面。Add a basic user interface.

准备数据访问类Prepare the data access class

从 UWP 项目中,添加对解决方案中的 DataAccessLibrary 项目的引用。From your UWP project, add a reference to the DataAccessLibrary project in your solution.

1218cc74ec53b5d314661e26c110a06c.png

在 UWP 项目中,将以下 using 语句添加到 App.xaml.cs 和 MainPage.xaml.cs 文件。Add the following using statement to the App.xaml.cs and MainPage.xaml.cs files in your UWP project.

using DataAccessLibrary;

在 DataAccessLibrary 解决方案中打开 DataAccess 类并将其设为静态。Open the DataAccess class in your DataAccessLibrary solution and make that class static.

备注

尽管我们的示例将数据访问代码放在静态类中,但这只是一个设计选择,并且是全凭自愿。While our example will place data access code in a static class, it's just a design choice and is completely optional.

namespace DataAccessLibrary

{

public static class DataAccess

{

}

}

将以下 using 语句添加到此文件顶部。Add the following using statements to the top of this file.

using Microsoft.Data.Sqlite;

using System.Collections.Generic;

初始化 SQLite 数据库Initialize the SQLite database

向 DataAccess 类添加一个初始化 SQLite 数据库的方法。Add a method to the DataAccess class that initializes the SQLite database.

public async static void InitializeDatabase()

{

await ApplicationData.Current.LocalFolder.CreateFileAsync("sqliteSample.db", CreationCollisionOption.OpenIfExists);

string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");

using (SqliteConnection db =

new SqliteConnection($"Filename={dbpath}"))

{

db.Open();

String tableCommand = "CREATE TABLE IF NOT " +

"EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " +

"Text_Entry NVARCHAR(2048) NULL)";

SqliteCommand createTable = new SqliteCommand(tableCommand, db);

createTable.ExecuteReader();

}

}

此代码将创建 SQLite 数据库并将其存储在应用程序的本地数据存储区中。This code creates the SQLite database and stores it in the application's local data store.

在此示例中,我们将数据库命名为 sqlliteSample.db,但你可以使用任何想要的名称,只要你在你实例化的所有 SqliteConnection 对象中使用该名称。In this example, we name the database sqlliteSample.db but you can use whatever name you want as long as you use that name in all SqliteConnection objects that you instantiate.

在 UWP 项目的 App.xaml.cs 文件的构造函数中,调用 DataAccess 类的 InitializeDatabase 方法。In the constructor of the App.xaml.cs file of your UWP project, call the InitializeDatabase method of the DataAccess class.

public App()

{

this.InitializeComponent();

this.Suspending += OnSuspending;

DataAccess.InitializeDatabase();

}

将数据插入到 SQLite 数据库Insert data into the SQLite database

向 DataAccess 类添加一个将数据插入到 SQLite 数据库的方法。Add a method to the DataAccess class that inserts data into the SQLite database. 此代码在查询中使用参数以阻止 SQL 注入攻击。This code uses parameters in the query to prevent SQL injection attacks.

public static void AddData(string inputText)

{

string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");

using (SqliteConnection db =

new SqliteConnection($"Filename={dbpath}"))

{

db.Open();

SqliteCommand insertCommand = new SqliteCommand();

insertCommand.Connection = db;

// Use parameterized query to prevent SQL injection attacks

insertCommand.CommandText = "INSERT INTO MyTable VALUES (NULL, @Entry);";

insertCommand.Parameters.AddWithValue("@Entry", inputText);

insertCommand.ExecuteReader();

db.Close();

}

}

从 SQLite 数据库检索数据Retrieve data from the SQLite database

添加从 SQLite 数据库获取数据行的方法。Add a method that gets rows of data from a SQLite database.

public static List GetData()

{

List entries = new List();

string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");

using (SqliteConnection db =

new SqliteConnection($"Filename={dbpath}"))

{

db.Open();

SqliteCommand selectCommand = new SqliteCommand

("SELECT Text_Entry from MyTable", db);

SqliteDataReader query = selectCommand.ExecuteReader();

while (query.Read())

{

entries.Add(query.GetString(0));

}

db.Close();

}

return entries;

}

Read 方法将向前浏览返回的数据的行。The Read method advances through the rows of returned data. 如果有剩下的行,它将返回 true,否则返回 false。It returns true if there are rows left, otherwise it returns false.

GetString 方法返回字符串形式的指定列的值。The GetString method returns the value of the specified column as a string. 它将接受一个整数值,该值表示所需的数据的从零开始的列序号。It accepts an integer value that represents the zero-based column ordinal of the data that you want. You can use similar methods such as GetDataTime and GetBoolean. 请根据列包含的数据的类型选择方法。Choose a method based on what type of data the column contains.

在此例子中,序号参数并不重要,因为我们选择了单个列中的所有条目。The ordinal parameter isn't as important in this example because we are selecting all of the entries in a single column. 但是,如果多个列是你的查询的一部分,请使用序号值获取你要从中拉取数据的列。However, if multiple columns are part of your query, use the ordinal value to obtain the column you want to pull data from.

添加基本用户界面Add a basic user interface

在 UWP 项目的 MainPage.xaml 文件中,添加以下 XAML。In the MainPage.xaml file of the UWP project, add the following XAML.

Add

此基本用户界面为用户提供了 TextBox,可用于键入我们将添加到 SQLite 数据库的字符串。This basic user interface gives the user a TextBox that they can use to type a string that we'll add to the SQLite database. 我们要将此 UI 中的 Button 连接到事件处理程序,后者将从 SQLite 数据库检索数据然后在 ListView 中显示数据。We'll connect the Button in this UI to an event handler that will retrieve data from the SQLite database and then show that data in the ListView.

在 MainPage.xaml.cs 文件中,添加以下处理程序。In the MainPage.xaml.cs file, add the following handler. 这是我们关联到 UI 中的 Button 的 Click事件的方法。This is the method that we associated with the Click event of the Button in the UI.

private void AddData(object sender, RoutedEventArgs e)

{

DataAccess.AddData(Input_Box.Text);

Output.ItemsSource = DataAccess.GetData();

}

完成了。That's it. 探索 Microsoft.Data.Sqlite 以了解 SQLite 数据库的其他功能。Explore the Microsoft.Data.Sqlite to see what other things you can do with your SQLite database. 查看下面的链接,了解在 UWP 应用中使用数据的其他方法。Check out the links below to learn about other ways to use data in your UWP app.

后续步骤Next steps

将应用直接连接到 SQL Server 数据库Connect your app directly to a SQL Server database

在跨不同平台的不同应用之间共享代码Share code between different apps across different platforms

使用 Azure SQL 后端添加大纲/细节页面Add master detail pages with Azure SQL back ends

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值