应用可以直接连接到SQL Server数据库,然后使用 System.Data.SqlClient 命名空间中的类存储和检索数据。
入门
在本指南中,我们将向你展示在使用Windows App SDK的应用中执行此作的一种方法。 如果将 Northwind 示例数据库安装到SQL Server实例上,然后使用这些代码片段,最终会获得一个显示 Northwind 示例数据库中产品的基本 UI。
提示
还可以从SQL Server示例GitHub存储库获取用于创建Northwind和pubs示例数据库的脚本。
本指南中显示的代码片段基于此 UWP 示例应用。
首先,配置解决方案
若要将应用直接连接到SQL Server数据库,应用可以面向Windows App SDK支持的任何最低版本的Windows。 可以在项目的属性页中找到该信息。
- 在清单设计器中打开Windows App SDK项目的 Package.appxmanifest 文件。
- 在功能选项卡中,如果您使用 Windows 验证您的 SQL Server,请选中企业身份验证复选框。
重要
还需要选择 Internet (客户端和Server)、Internet(Client)和Private Networks(客户端和)Server),无论是否使用Windows身份验证。
在SQL Server数据库中添加和检索数据
在本部分中,我们将执行以下操作:
1️⃣ 添加连接字符串。
2️⃣ 创建用于保存产品数据的类。
3️⃣ 从 SQL Server 数据库中检索产品。
4️⃣ 添加基本用户界面。
5️⃣ 使用产品填充 UI。
注意事项
本节介绍了一种组织你的数据访问代码的方法。 它仅用于提供一个示例,说明如何使用 System.Data.SqlClient 存储和检索SQL Server数据库中的数据。 你可以采用对你的应用程序设计最有意义的任何方式组织你的代码。
添加连接字符串
在 App.xaml.cs 文件中,向 App 类添加一个属性,该属性为解决方案中的其他类提供对connection string的访问权限。
我们的连接字符串指向 SQL Server Express 实例中的 Northwind 数据库。 此代码片段中的connection string假定在安装 SQL Server Express 时将默认实例名称保留为 SQLEXPRESS。 可以更改connection string以匹配SQL Server实例、数据库和身份验证方法。
sealed partial class App : Application
{
// Connection string for using Windows Authentication.
private string connectionString =
@"Data Source=.\SQLEXPRESS;Initial Catalog=NORTHWIND;Integrated Security=SSPI";
public string ConnectionString { get => connectionString; set => connectionString = value; }
...
}
重要
在生产应用程序中,连接信息应安全地存储在应用配置中(请参阅 使用 Visual Studio Connected Services 添加Azure App Configuration)。 连接字符串和其他机密永远不应该被硬编码。
创建用于保存产品数据的类
我们将创建一个实现 INotifyPropertyChanged 事件的类,以便我们可以将 XAML UI 中的属性绑定到此类中的属性。
public class Product : INotifyPropertyChanged
{
public int ProductID { get; set; }
public string ProductCode { get { return ProductID.ToString(); } }
public string ProductName { get; set; }
public string QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public string UnitPriceString { get { return UnitPrice.ToString("######.00"); } }
public int UnitsInStock { get; set; }
public string UnitsInStockString { get { return UnitsInStock.ToString("#####0"); } }
public int CategoryId { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
从 SQL Server 数据库中检索产品
在Windows App SDK项目的 MainWindow.xaml.cs 文件中,创建一个从 Northwind 示例数据库获取产品的方法,然后将其作为 ObservableCollection 集合返回Product实例。
public ObservableCollection<Product> GetProducts(string connectionString)
{
const string GetProductsQuery = "select ProductID, ProductName, QuantityPerUnit," +
" UnitPrice, UnitsInStock, Products.CategoryID " +
" from Products inner join Categories on Products.CategoryID = Categories.CategoryID " +
" where Discontinued = 0";
var products = new ObservableCollection<Product>();
try
{
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetProductsQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var product = new Product();
product.ProductID = reader.GetInt32(0);
product.ProductName = reader.GetString(1);
product.QuantityPerUnit = reader.GetString(2);
product.UnitPrice = reader.GetDecimal(3);
product.UnitsInStock = reader.GetInt16(4);
product.CategoryId = reader.GetInt32(5);
products.Add(product);
}
}
}
}
}
return products;
}
catch (Exception eSql)
{
Debug.WriteLine($"Exception: {eSql.Message}");
}
return null;
}
添加基本用户界面
将以下 XAML 添加到Windows App SDK项目的 MainWindow.xaml 文件中。
此 XAML 创建一个 ListView 以显示在上一个代码片段中返回的每个产品,并将每个行 ListView 的属性绑定到我们在类中 Product 定义的属性。
<Grid Background="{ThemeResource SystemControlAcrylicWindowBrush}">
<RelativePanel>
<ListView Name="InventoryList"
SelectionMode="Single"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.IsVerticalRailEnabled="True"
ScrollViewer.VerticalScrollMode="Enabled"
ScrollViewer.HorizontalScrollMode="Enabled"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.IsHorizontalRailEnabled="True"
Margin="20">
<ListView.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="ID" Margin="8,0" Width="50" Foreground="DarkRed" />
<TextBlock Text="Product description" Width="300" Foreground="DarkRed" />
<TextBlock Text="Packaging" Width="200" Foreground="DarkRed" />
<TextBlock Text="Price" Width="80" Foreground="DarkRed" />
<TextBlock Text="In stock" Width="80" Foreground="DarkRed" />
</StackPanel>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Product">
<StackPanel Orientation="Horizontal" >
<TextBlock Name="ItemId"
Text="{x:Bind ProductCode}"
Width="50" />
<TextBlock Name="ItemName"
Text="{x:Bind ProductName}"
Width="300" />
<TextBlock Text="{x:Bind QuantityPerUnit}"
Width="200" />
<TextBlock Text="{x:Bind UnitPriceString}"
Width="80" />
<TextBlock Text="{x:Bind UnitsInStockString}"
Width="80" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</RelativePanel>
</Grid>
在 ListView 中显示产品
打开MainWindow.xaml.cs文件,将代码添加到MainWindow类的构造函数中,以设置ListView的ItemSource属性为ObservableCollection实例。
public MainWindow()
{
this.InitializeComponent();
InventoryList.ItemsSource = GetProducts((App.Current as App).ConnectionString);
}
启动项目并看到来自 Northwind 示例数据库的产品出现在 UI 中。
浏览 System.Data.SqlClient 命名空间,了解在 SQL Server 数据库中可以对数据执行的其他操作。
提示
尝试询问 Microsoft Copilot 以获取有关 SQL 查询的帮助。 Copilot可帮助你编写 SQL 查询,并建议改进代码的方法。
连接数据库时遇到问题?
在大多数情况下,需要更改SQL Server配置的某些方面。 如果能够从其他类型的桌面应用程序(例如Windows Forms或WPF应用程序)连接到数据库,请确保已为SQL Server启用 TCP/IP。 可以在 计算机管理控制台 中执行此作。 (有关详细信息,请参阅 Windows 工具/管理工具。
然后,请确保SQL Server浏览器服务正在运行。