在 UWP 應用程式中使用 SQL Server 資料庫

您的應用程式可以直接連線到 SQL Server 資料庫,然後使用 System.Data.SqlClient 命名空間中的類別儲存和擷取資料。

本指南會說明做法。 如果您在 SQL Server 執行個體上安裝 Northwind 範例資料庫,然後使用這些程式碼片段,就會獲得基本 UI,可供顯示 Northwind 範例資料庫中的產品。

Northwind products

本指南中顯示的程式碼片段是以這個更加完整的範例為基準。

先設定解決方案

若要將您的應用程式直接連線到 SQL Server 資料庫,請確定您專案的最低版本目標為 Windows 10 Fall Creators Update (組建 16299) 或更新版本。 您可以在 UWP 專案的屬性頁面中找到該資訊。

Minimum version of the Windows SDK

在資訊清單設計工具中,開啟 UWP 專案的 Package.appxmanifest 檔案。

如果要使用 Windows 驗證對 SQL Server 進行驗證,請在 [功能] 索引標籤中,選取 [企業驗證] 核取方塊。

Enterprise Authentication Capability

重要

不論您是否使用 Windows 驗證,也都必須選取 [網際網路 (用戶端和伺服器)]、[網際網路 (用戶端)] 和 [私人網路 (用戶端和伺服器)]

在 SQL Server 資料庫中新增和擷取資料

本節中,我們會進行下列事項:

1️⃣ 新增連接字串。

2️⃣ 建立類別來保存產品資料。

3️⃣ 從 SQL Server 資料庫擷取產品。

4️⃣ 新增基本使用者介面。

5️⃣ 使用產品填入 UI。

注意

本節會說明資料存取碼的組織方式。 主要目的僅在於示範如何使用 System.Data.SqlClient 儲存和擷取 SQL Server 資料庫中的資料。 可以採用最適合您應用程式設計的方式來組織程式碼。

新增連接字串

App.xaml.cs 檔案中,新增屬性至 App 類別,讓解決方案中的其他類別能夠存取該連接字串。

連接字串會指向 SQL Server Express 執行個體中的 Northwind 資料庫。

sealed partial class App : Application
{
    // Connection string for using Windows Authentication.
    private string connectionString =
        @"Data Source=YourServerName\SQLEXPRESS;Initial Catalog=NORTHWIND;Integrated Security=SSPI";

    // This is an example connection string for using SQL Server Authentication.
    // private string connectionString =
    //     @"Data Source=YourServerName\YourInstanceName;Initial Catalog=DatabaseName; User Id=XXXXX; Password=XXXXX";

    public string ConnectionString { get => connectionString; set => connectionString = value; }

    ...
}

建立類別來保留產品資料

我們要建立類別來實作 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 資料庫擷取產品

在 UWP 專案的 MainPage.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 新增至 UWP 專案的 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 中顯示產品

開啟 MainPage.xaml.cs 檔案,並將程式碼新增至 MainPage 類別的建構函式,該類別會將 ListViewItemSource 屬性設為 Product 執行個體的 ObservableCollection

public MainPage()
{
    this.InitializeComponent();
    InventoryList.ItemsSource = GetProducts((App.Current as App).ConnectionString);
}

啟動專案,可在 UI 所顯示的 Northwind 範例資料庫中看到產品。

Northwind products

探索 System.Data.SqlClient 命名空間,了解還能如何處理 SQL Server 資料庫中的資料。

無法連線到您的資料庫?

在大部分情況中,SQL Server 設定有些方面需要變更。 如果您能從另一種桌面應用程式 (例如 Windows Forms 或 WPF 應用程式) 連線到您的資料庫,請確定您啟用 SQL Server 的 TCP/IP。 您可以在 [電腦管理] 主控台執行。 (如需詳細資訊,請參閱 Windows 工具/系統管理工具)

Computer Management

然後,請確定您的 SQL Server Browser 服務正在執行。

SQL Server Browser Service

下一步

使用輕量資料庫將資料儲存在使用者的裝置上

請參閱在 UWP 應用程式中使用 SQLite 資料庫

在多個平台的不同應用程式之間共用程式碼

請參閱在桌面應用程式與 UWP 之間共用程式碼

在 Azure SQL 後端新增主要詳細資料頁面

請參閱客戶訂單資料庫範例 (英文)。