我正在尝试从通用 Windows 应用程序连接到本地 MS SQL 数据库。我正在使用 UWP 制作 LOB 应用程序,以支持桌面、平板电脑和移动设备使用。当尝试连接到本地(内联网)SQL Server 数据库时,我习惯于使用sql连接连接到本地服务器,但由于 SqlConnection 不包含在 UWP 中使用的 .NET 子集中,那么在使用 UWP 时如何完成此操作?
我已经看过了微软官方样本以及操作指南,并且没有发现任何有关非 Azure 数据库的数据库连接的信息。数据库连接看起来这可能是一个好方法,但不能使用,因为它是抽象的,而且它是子项(例如数据.SqlClient.SqlConnection)似乎未包含在 UWP 的 .NET 子集中。
我在这里错过了一些非常明显的东西吗?顺便说一句,有人知道 UWP 的良好命名空间参考吗?
编辑非重复:建议作为重复的链接问题适用于 Windows 8/8.1 应用程序,虽然存在一些相似之处,但该问题接受的答案中的代码不适用于 UWP。不过,原理是相同的,但对于使用 UWP 构建的 Windows 10 应用程序应该有更好的技术参考。
通过 Windows 10 Fall Creators Update(内部版本 16299),UWP 应用程序现在可以通过标准 NET 类 (System.Data.SqlClient) 直接访问 SQL Server - 这要归功于 UWP 中新增的对 .NET Standard 2.0 的支持。
这是 Northwind UWP 演示应用程序:https://github.com/StefanWickDev/IgniteDemos
我们已于 2017 年 9 月在 Microsoft Ignite 上展示了此演示,以下是我们的会议记录(跳至 23:00 查看 SQL 演示):https://myignite.microsoft.com/sessions/53541
以下是从 Northwind 数据库检索产品的代码(请参阅演示中的 DataHelper.cs)。请注意,由于 .NET Standard 2.0,它与您为 Winforms 或 WPF 应用程序编写的代码完全相同:
public static ProductList 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 ProductList();
try
{
using (SqlConnection 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;
}
如果您需要支持秋季创意者更新之前的版本,您还可以通过桌面桥从 UWP 应用程序包调用 SqlClient API。我在这里发布了一个示例:https://github.com/Microsoft/DesktopBridgeToUWP-Samples/tree/master/Samples/SQLServer
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)