SqlConnection from SqlClient not being recognized when trying to connect to MSSQL from a Unity Project through Microsoft Visual Studio 2022

  Kiến thức lập trình

I am trying to connect my Unity project with an MSSQL database using MSVS2022, but when typing my code, I get the following error:

Severity Code Description Project File Line Suppression State
Error CS1069 The type name ‘SqlConnection’ could not be found in the namespace ‘System.Data.SqlClient’. This type has been forwarded to assembly ‘System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ Consider adding a reference to that assembly. Assembly-CSharp C:UsersgerarUnityMSSQL_pruebaAssetsScriptsGenerateLabels.cs 21 Active
Also, since I am new to .net, I am not sure what type is being used (.net/.net-core), I am not diving into it as I am only trying to use it for Unity.

This is the code I am using:

using System;
using System.Data;
**using System.Data.SqlClient;**
using UnityEngine;
using static UnityEngine.UIElements.UxmlAttributeDescription;
public class GenerateLabels : MonoBehaviour
{
    public string UserName; //to share the variable with onGUI function
 void Start()
    {
        Debug.Log("Hello world !!!"); // Show message on the GameObject Console
        string connectionString =
           "Server=XX;" + 
           "Database=XX;" + 
           "User ID=XX;" + 
           "Password=XX;"; 
        IDbConnection dbcon;
        **using (dbcon = new SqlConnection(connectionString))**
        {
            dbcon.Open();
            using (IDbCommand dbcmd = dbcon.CreateCommand())
            {
                string sql = "SELECT Name, UserPrincipalName FROM Users WHERE Id=1";
                dbcmd.CommandText = sql;
                using (IDataReader reader = dbcmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string FirstName = (string)reader["Name"];
                        string LastName = (string)reader["UserPrincipalName"];
                        UserName = "Name: " + FirstName + " " + LastName;
                        Debug.Log(UserName); //Display username in GameObject Console
                    }
                }
            }
        }
    }
    void OnGUI()
    {
        //Show database values on GameObject Scene
        Rect position = new Rect(60, 20, 400, 60);
        GUI.Label(position, UserName);
    }
}

I researched the same issue online, and many solutions said to install the NuGet package “System.Data.SqlClient” by Microsoft. I had already installed it in its most recent stable version (4.8.6), but the error does not disappear, it’s like if “SqlConnection” didn’t exist inside it.

New contributor

Gerardo Leiva Diaz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT