直接访问一个在Xamarin.Forms SQL Server数据库 [英] Accessing directly a Sql Server Database in Xamarin.Forms
问题描述
我在使用Xamarin只是一个初学者。我创建了一个示例Xamarin.Forms便携式项目在Visual Studio 2013年,我想知道是否有可能访问MS SQL数据库,并显示它到我的手机?如果是,可以请你给我我怎么会做一些这方面的指导?非常感谢。我希望有人能帮助我。
您不能直接从您的PCL项目访问SQL服务器Xamarin.Forms因为 System.Data.SqlClient的
不适用于PCL。
不过你可以通过依存服务做到
>公共接口IDbDataFetcher
{
字符串的GetData(字符串conn)的;
}
然后在你的Android项目实现服务接口
[汇编:依赖(typeof运算(DbFetcher))]
命名空间App.Droid.Services
{
类DbFetcher: IDbDataFetcher
{
公开名单<串GT;的GetData使用(字符串conn)的
{
(SqlConnection的连接=新的SqlConnection(康涅狄格州))
{
的SqlCommand命令=新的SqlCommand(SELECT * FROM的smuser ,连接);
试
{
connection.Open();
SqlDataReader的读卡器= Command.ExecuteReader却();
而(reader.Read())
{
data.Add(读者[0]的ToString());
}
reader.Close();
}
赶上(异常前)
{
//Console.WriteLine(ex.Message);
}
}
返回数据;
}
}
}
虽然这是一个解决方案,它是的坏之一。始终使用Web服务,为您的移动应用
I'm just a beginner in using Xamarin. I created a sample Xamarin.Forms Portable project in Visual Studio 2013. I want to know if it is possible to access an MS SQL database and display it to my mobile phone? If Yes, can you please give me some instruction on how am I going to do this? Thanks a lot. I hope someone will help me.
You cannot access directly an sql server from your pcl project in Xamarin.Forms because System.Data.SqlClient
is not available on pcl.
But you can do it through a dependency service.
First in you PCL project declare you service
public interface IDbDataFetcher
{
string GetData(string conn);
}
Then on you Android project implement the service 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;
}
}
}
Although it is a solution it is a bad one. Always consume web services for your mobile apps
这篇关于直接访问一个在Xamarin.Forms SQL Server数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!