Search code examples
c#sql-serverdockerparallels

Can't Connect C# with SQL Server


I am trying to write a program which interacts with my SQL Server database. I am programming in C# on Parallels on my Mac and SQL Server is running via Docker.

But I just can't connect. I am just getting the same error every time I try.

I have already tried to allow the remote access on SQL Server with:

EXEC sp_configure 'remote access', 1 ;  
GO  
RECONFIGURE ;  
GO 

but this does not solve my problem.

Here is my C# code:

main Class

Database database;

public Form1()
{
    InitializeComponent();
    database = new Database("localhost\\MSSQLSERVER", "user1", "topsecret", "master"); // \
}

private void connect_button_Click(object sender, EventArgs e)
{
    database.Connect();
}

Database class:

class Database
{
    SqlConnectionStringBuilder builder;
    SqlConnection connection;

    public Database(string source, string userid, string password, string initialcatalog){
        this.builder = new SqlConnectionStringBuilder();
        this.builder.DataSource = source;
        this.builder.UserID = userid;
        this.builder.Password = password;
        this.builder.InitialCatalog = initialcatalog;
    }

    public void Connect()
    {
        try 
        {
            // Connect to SQL
            Console.WriteLine("Connecting to SQL Server ... ");
            this.connection = new SqlConnection(this.builder.ConnectionString);
            connection.Open();
            Console.WriteLine("Connected");
        }
        catch(SqlException sqle)
        {
            Console.WriteLine(sqle.Message);
        }
    }
}

And I am always getting this error:

Network-related or instance-specific error when connecting to SQL Server. The server was not found or can not be accessed. Verify that the instance name is correct and that SQL Server allows remote connections. (provider: SQL Network Interfaces, error: 25 - connection string invalid)


Solution

  • It was Problem with Parallels, because Paralles can not access to localhost. So i had to define the IP from Parallels in Visual Studio like this:

    database = new Database("10.211.55.2", "user1", "topsecret", "Time");