简体   繁体   中英

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.

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.

  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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM