在 Xamarin.Forms 中直接访问 Sql Server 数据库 [英] Accessing directly a Sql Server Database in Xamarin.Forms

查看:137
本文介绍了在 Xamarin.Forms 中直接访问 Sql Server 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是使用 Xamarin 的初学者.我在 Visual Studio 2013 中创建了一个示例 Xamarin.Forms Portable 项目.我想知道是否可以访问 MS SQL 数据库并将其显示到我的手机上?如果是,您能否给我一些有关我将如何执行此操作的说明?非常感谢.我希望有人能帮助我.

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.

推荐答案

您无法从 Xamarin.Forms 中的 pcl 项目直接访问 sql server,因为 System.Data.SqlClient 在 pcl 上不可用.

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.

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

First in you PCL project declare you service

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆