'Using SqlConnection in Xamarin.Forms?

Can I use SqlConnection in Xamarin.Forms?

I tend to use this in Windows and Web applications developed in Visual Studio, but I don't know how it would work in Xamarin.

I get namespace name does not exist with using System.Data.SQLClient;, even after adding references Mono.Data.Sqlite and System.Data.

        SqlConnection conn = new SqlConnection(ConnectionString);
        SqlDataAdapter da = new SqlDataAdapter();
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = SQL;
        da.SelectCommand = cmd;
        DataSet ds = new DataSet();

        conn.Open();

        da.Fill(ds);
        conn.Close();

Can this code snippet be used or does it need to be done another way?

I'm adding the code to a class that's part of the Xamarin.Forms project.



Solution 1:[1]

There is no way to make SQL connection. In general platforms supported by Xamarin have no support for traditional databases (except for SQLite if you can count it in there), so such connection wouldn't make sense.

If you want to connect to real databases in Xamarin, those databases must have the web interface. And again that is not Xamarin limitation but rather limitation of nearly all supported platforms.

Solution 2:[2]

  1. Right click on your project,
  2. Select Nuget packages
  3. Look for "System.Data.SqlClient
  4. Install it And you are good to go for now.

Solution 3:[3]

I didn't try in Xamarin.Forms only in Xamarin.Android and I found it's possible using a simple trick. First I tried without success adding NuGet package System.Data.SqlClient directly to the Android project but neither adding "using System.Data.SqlClient;" it was possible for me to create a SqlConnection obj. I solved adding both new standard 2.0 library project and the above NuGet Package to this second project and creating all the connection classes inside this one and then added to the first Android project with Add --> Reference and pointed to the library and all works ok.

Solution 4:[4]

For Xamarin it looks like you need to go one level higher in the reference - Right click on Reference>Add References - scroll down to System.Data and check the box (click OK). Error should go away.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivan Ičin
Solution 2 Flaubert TAGU
Solution 3 lucdm
Solution 4 Rob Turner