我只是使用 Xamarin 的初学者。我在 Visual Studio 2013 中创建了一个示例 Xamarin.Forms Portable 项目。我想知道是否可以访问 MS SQL 数据库并将其显示到我的手机上?如果是,你能给我一些关于我将如何做到这一点的指导吗?多谢。我希望有人能帮助我。
最佳答案
您无法从 Xamarin.Forms 中的 pcl 项目直接访问 sql server,因为 System.Data.SqlClient
在 pcl 上不可用。
但您可以通过依赖服务来完成。
首先在您的 PCL 项目中声明您的服务
public interface IDbDataFetcher
{
string GetData(string conn);
}
然后在你的Android项目上实现服务接口(interface)
[assembly: Dependency(typeof(DbFetcher))]
namespace App.Droid.Services
{
class DbFetcher : IDbDataFetcher
{
public List<string> GetData(string conn)
{
using (SqlConnection connection = new SqlConnection(conn))
{
SqlCommand command = new SqlCommand("select * from smuser", connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
data.Add(reader[0].ToString());
}
reader.Close();
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
return data;
}
}
}
虽然这是一个解决方案,但它是一个糟糕的解决方案。始终为您的移动应用程序使用 Web 服务
关于c# - 在 Xamarin.Forms 中直接访问 Sql Server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873020/