在 Windows 應用程式中使用 SQL Server 資料庫
您的應用程式可以直接連線到 SQL Server 資料庫,然後使用 System.Data.SqlClient 命名空間中的類別儲存和擷取資料。
開始使用
在本指南中,我們將示範在 Windows App SDK 應用程式中執行此動作的一種方式。 如果您在 SQL Server 執行個體上安裝 Northwind 範例資料庫,然後使用這些程式碼片段,就會獲得基本 UI,可供顯示 Northwind 範例資料庫中的產品。
提示
您也可以取得腳本,以從 SQL Server 範例 GitHub 存放庫建立 Northwind 和 pubs 範例資料庫。
本指南中顯示的程式碼片段是以這個 UWP 範例應用程式為基準。
先設定解決方案
若要將應用程式直接連線到 SQL Server 資料庫,您的應用程式可以將 Windows App SDK 支援的任何最低 Windows 版本設為目標。 您可以在專案的屬性頁面中找到該資訊。
- 在資訊清單設計工具中,開啟 Windows App SDK 專案的 Package.appxmanifest 檔案。
- 如果要使用 Windows 驗證對 SQL Server 進行驗證,請在 [功能] 索引標籤中,選取 [企業驗證] 核取方塊。
重要
不論您是否使用 Windows 驗證,也都必須選取 [網際網路 (用戶端和伺服器)]、[網際網路 (用戶端)] 和 [私人網路 (用戶端和伺服器)]。
在 SQL Server 資料庫中新增和擷取資料
本節中,我們會進行下列事項:
1️⃣ 新增連接字串。
2️⃣ 建立類別來保存產品資料。
3️⃣ 從 SQL Server 資料庫擷取產品。
4️⃣ 新增基本使用者介面。
5️⃣ 使用產品填入 UI。
注意
本節會說明資料存取碼的組織方式。 主要目的僅在於示範如何使用 System.Data.SqlClient 儲存和擷取 SQL Server 資料庫中的資料。 可以採用最適合您應用程式設計的方式來組織程式碼。
新增連接字串
在 App.xaml.cs 檔案中,新增屬性至 App
類別,讓解決方案中的其他類別能夠存取該連接字串。
連接字串會指向 SQL Server Express 執行個體中的 Northwind 資料庫。 此代碼段中的 連接字串 假設您在安裝 SQL Server Express 時保留預設實例名稱SQLEXPRESS
。 您可以變更 連接字串,以符合您的 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 已連線的服務新增 Azure 應用程式組態)。 連接字串和其他祕密絕不可以硬式編碼。
建立類別來保留產品資料
我們要建立類別來實作 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 範例資料庫中取得產品,然後將其做為 Product
執行個體的 ObservableCollection 集合傳回。
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 專案的 MainPage.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 屬性設為 Product
執行個體的 ObservableCollection。
public MainWindow()
{
this.InitializeComponent();
InventoryList.ItemsSource = GetProducts((App.Current as App).ConnectionString);
}
啟動專案,可在 UI 所顯示的 Northwind 範例資料庫中看到產品。
探索 System.Data.SqlClient 命名空間,了解還能如何處理 SQL Server 資料庫中的資料。
提示
請嘗試詢問 Microsoft Copilot 以取得 SQL 查詢的說明。 Copilot 可協助您撰寫 SQL 查詢,並建議改善程式碼的方法。
無法連線到您的資料庫?
在大部分情況中,SQL Server 設定有些方面需要變更。 如果您能從另一種桌面應用程式 (例如 Windows Forms 或 WPF 應用程式) 連線到您的資料庫,請確定您啟用 SQL Server 的 TCP/IP。 您可以在 [電腦管理] 主控台執行。 (如需詳細資訊,請參閱 Windows 工具/系統管理工具)。
然後,請確定您的 SQL Server Browser 服務正在執行。