I am trying to connect my Unity project with a SQL Server database using VS 2022, but when typing my code, I get the following error:
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; // Here I use SqlClient
using UnityEngine;
using static UnityEngine.UIElements.UxmlAttributeDescription;
public class GenerateLabels : MonoBehaviour
{
public string UserName;
function void Start()
{
Debug.Log("Hello world !!!");
string connectionString =
"Server=XX;" +
"Database=XX;" +
"User ID=XX;" +
"Password=XX;";
IDbConnection dbcon;
using (dbcon = new SqlConnection(connectionString)) // This line is where the error is displayed.
{
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);
}
}
}
}
}
void OnGUI()
{
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.
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.
1