I am trying to connect to a local host sql server 2008 express server. I am running my c# asp.net code locally as well (testing before I connect to dev servers). I cannot get the code to connect to the database. I copied the connection string from the properties of the database created within visual studio 2010, and tried using that, but it did not work. Then I used:
//Build the connection
SqlConnectionStringBuilder bldr = new SqlConnectionStringBuilder();
//Put your server or server\instance name here. Likely YourComputerName\SQLExpress
bldr.DataSource = "(localhost)/SQLEXPRESS;";
//Attach DB Filename
bldr.AttachDBFilename = "C:/Documents and Settings/1091912/My Documents/Visual Studio 2010/WebSites/BrokerBuy/App_Data/BrokerBuy.mdf";
//User Instance
bldr.UserInstance = true;
//Whether or not a password is required.
bldr.IntegratedSecurity = true;
SqlConnection connectionString = new SqlConnection(bldr.ConnectionString);
connectionString.Open();
But this does not work either. I have also tried ./SQLEXPRESS for my datasource name, but this did not work either. The error that comes up is :
"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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
I have also checked to ensure sql server express is running (it is) and that all connections but via are enabled. I cannot get the connection to work. Any ideas?
There's a few problems with your code.
The first is (localhost)
is not a valid token. You can use (local)
or even better yet just .
.
The second is your path is using forward-slashes instead of backslashes. Though newer versions of Windows support this for *NIX compatibility, the database drivers may or may not depending on how they parse the path internally.
Here's some example code that should work:
//Build the connection
SqlConnectionStringBuilder bldr = new SqlConnectionStringBuilder();
//Put your server or server\instance name here. Likely YourComputerName\SQLExpress
bldr.DataSource = ".\\SQLEXPRESS";
//Attach DB Filename
bldr.AttachDBFilename = bldr.AttachDBFilename = @"C:\Documents and Settings\1091912\My Documents\Visual Studio 2010\WebSites\BrokerBuy\App_Data\BrokerBuy.mdf";
//User Instance
bldr.UserInstance = true;
//Whether or not a password is required.
bldr.IntegratedSecurity = true;
SqlConnection connectionString = new SqlConnection(bldr.ConnectionString);
connectionString.Open();