SqlConnection SocketException only in Unity

I have an SQL server database running locally on SQL server management 18

When I run the following script to make a query in a non-unity console application, it works great

   static void Main(string[] args)
            {
                SqlConnection connection = new SqlConnection(@"Server=localhost\SQLEXPRESS;Database=MY_DATABASE;User ID=sa;Password=;");
                connection.Open();
                SqlCommand command = new SqlCommand("SELECT * FROM dataitems", connection);
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(reader[2]);
                    }
    
                }
                
            }

However, when I run the same code in Unity, I get the error: “SocketException: An existing connection was forcibly closed by the remote host.” (In both editor and built versions)

void Start()
    {
        SqlConnection connection = new SqlConnection(@"Server=localhost\SQLEXPRESS;Database=MY_DATABASE;User ID=sa;Password=;");
        connection.Open();
        SqlCommand command = new SqlCommand("SELECT * FROM dataitems", connection);
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                Debug.Log(reader[2]);
            }

        }
}

Why is this happening on my machine? On other machines there doesn’t seem to be a problem.

Common solutions I have already addressed:

  • My firewall is switched off
  • TCP/IP is enabled in the server network configuration

I fixed it! And I’m going to be a good person and return to this post and share it with any lost travellers.

I needed to enable the server brower

to do this: go into Sql Server Configuration Manager, click Sql Server Services, right click Sql Server Browser, Properties, Service, Start Mode Automatic, Apply, right click again, Start.