The right connection string for Remote SQL server for C#

Lucas Juan picture Lucas Juan · Dec 13, 2013 · Viewed 67.2k times · Source

I just want to know the right sql connection string for a remote sql server express edition.

This is what I got but I got some problems

 SqlConnection cs = new SqlConnection(@"Data Source=(IP Address)\PC-NAME\SQLEXPRESS,1433;Network Library=DBMSSOCN;Initial Catalog=dbase;User ID=sa;Password=password");

I got this error in my C# debugger:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

Thanks in advance!

Answer

Corey picture Corey · Dec 13, 2013

From your comment:

The IP address is the static IP address. I am trying to connect outside the building.

If the database you are trying to connect to is on a computer behind a [router/firewall/modem] that has the target address, you will need to use port forwarding on the [router/firewall/modem] to forward all connections on TCP port 1433 through to the target machine.

If you are trying to connect to a home computer behind an ADSL modem with a static IP address, your ADSL modem needs to be configured with port forwarding to connect the external port 1433 with the same port on the internal address. This must be done on the modem, and cannot be done just with a connection string.

Let's say you have an ADSL modem listening on 127.2.3.4 (invalid address for demonstration only) and a PC behind that with an IP address of 192.168.0.100. Configure the modem to forward port 1433 to 192.168.0.100:1433 (how will depend on make and model of modem). Then your connection string would be:

Data Source=127.2.3.4\SQLEXPRESS,1433;Network Library=DBMSSOCN;Initial Catalog=dbase;User ID=sa;Password=password

Assuming that SQLEXPRESS is the only database instance on the server, and since port 1433 is the default, you could use the simpler:

Data Source=tcp:127.2.3.4;Initial Catalog=dbase;User ID=sa;Password=password

The Network Library=DBMSSOCN specification is replaced with tcp: and defaults are assumed for instance and port.