【问题标题】:Accessing directly a Sql Server Database in Xamarin.Forms在 Xamarin.Forms 中直接访问 Sql Server 数据库
【发布时间】:2016-10-18 18:53:30
【问题描述】:

我只是使用 Xamarin 的初学者。我在 Visual Studio 2013 中创建了一个示例 Xamarin.Forms Portable 项目。我想知道是否可以访问 MS SQL 数据库并将其显示到我的手机上?如果是,你能给我一些关于我将如何做到这一点的指导吗?非常感谢。我希望有人能帮助我。

【问题讨论】:

  • 是的你can
  • @Martheen 感谢您的回答。你能告诉我我将如何做到这一点吗?
  • 这不是 stackoverflow 的用途。我提供的链接包含足够的说明。先试一试,写代码,然后问你是否发现了问题。
  • @Martheen 你说的链接在哪里?
  • “can”字是可点击的

标签: c# sql-server database xamarin xamarin.forms


【解决方案1】:

您无法从 Xamarin.Forms 中的 pcl 项目直接访问 sql 服务器,因为在 pcl 上没有System.Data.SqlClient

但是您可以通过依赖服务来做到这一点。

首先在你的 PCL 项目中声明你的服务

public interface IDbDataFetcher
    {
        string GetData(string conn);
    }

然后在你的 Android 项目上实现服务接口

[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;
        }
    }
}

虽然这是一个解决方案,但它是一个糟糕的解决方案。始终为您的移动应用使用网络服务

【讨论】:

  • 感谢先生的回答。我创建了一个示例项目并尝试使用我在教程中看过的 REST Web 服务 API。并与其他资源一起检查。他们说我在代码中没有错误,但可能在绑定中。由于我只是使用 Xamarin 的新手,因此我无法找出问题的原因。还是可以查一下吗?非常感谢。
  • @Jaycee,你能提供你的教程地址吗?
  • @JayceeEvangelista,这段代码是否建立了连接并获取数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
相关资源
最近更新 更多