Question:
Connection String for SQL Server within Visual C# 2010 Express?
James T
2011-01-23 09:01:45 UTC
Im using Microsoft Visual C# 2010 Express and trying to connect to the SQL server in the code using an SqlConnection and SqlDataAdapter as shown in http://msdn.microsoft.com/en-us/library/ms228366%28v=vs.80%29.aspx (C# Read Database Example).
However, I'm getting an error:
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 thought it would be a connection string problem but I've tried many different combinations and cannot get anything to work.

my database is located in the usual project folder "C:\Users\Me\Documents\Visual Studio 2010\Projects\SRE5FM2011\SRE5FM2011\FootballDatabase.sdf" and I want to connect locally through my program.
Three answers:
Shahriar N
2011-01-24 18:58:50 UTC
To connect to SQL Server from C#.NET, you need to create a connection string such as below:



private SqlConnection connection;

private string connectionString =

@"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123";

connection = new SqlConnection( connectionString );



Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:

SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = @Cid", connection);



The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.



Next to execute the SQL queries in the database, you use the following methods:

ExecuteReader - to execute SELECT queries

ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.
2016-10-15 07:54:17 UTC
Sql Server 2010 Express
Petro
2011-01-24 09:01:08 UTC
I've managed to get exactly the same error by shutting down SQL Server and trying to connect to it afterwards... Make sure your database server is running.

Also you can find samples of connection strings here: http://www.connectionstrings.com/



Edit:

If you haven’t done this already, try to add your database to Visual Studio Server Explorer. If you are able to add database to Server Explorer and then can browse through database tables, your server is running and is OK. If you select database in server explorer window, in properties window you can find connection string that works 100%.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...