Accessing directly a Sql Server Database in Xamarin.Forms

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

Leave a Comment