Accessing directly a Sql Server Database in Xamarin.Forms

16,965

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

Share:
16,965
Jaycee Evangelista
Author by

Jaycee Evangelista

Updated on June 05, 2022

Comments

  • Jaycee Evangelista
    Jaycee Evangelista almost 2 years

    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.