Sunday, February 19, 2012

Can't connect to SQL server 2005 Express through Visual C# app

I've installed SQL server 2005 Express and set up a database called StockData. I'm running the following code in a visual C# windows app to test the connection:

System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;

DataTable tblSource = instance.GetDataSources();

string strSource = tblSource.Rows[0][0].ToString() + "/" + tblSource.Rows[0][1].ToString();

SqlConnection sqlConn = new SqlConnection();

sqlConn.ConnectionString = "Data Source=(local);Initial Catalog=StockData;Integrated Security=true";

sqlConn.Open();

I have verified that the SQLEXPRESS service is up and running. The strSource variable shows the machine and SQLEXPRESS instance name when I step through, so I know that the application is recognizing the service. But when I get to the "sqlConn.Open()" line, I get the following error message:

Message="An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
Source=".Net SqlClient Data Provider"
ErrorCode=-2146232060

Can anyone tell me what I'm doing wrong here? This is driving me nuts. Thanks.


Your connection string is specifying Data Source=(local) which is for a Default Instance of SQL Server, not a named instance, as is the case for SQL Express. You should be specifying Data Source=(local)\SQLEXPRESS.

You're pulling the server information into strSource and you mention that you've confirmed it's correct, so I'm not sure why you're not using strSource to set Data Source. Possibly you mistyped your connection string? I'm guessing you meant:

sqlConn.ConnectionString = "Data Source=" + strSource + ";Initial Catalog=StockData;Integrated Security=True"

Hope this helps.

Regards,

Mike Wachal
SQL Express team

Mark the best posts as Answers!

No comments:

Post a Comment