C# and SQL Server connection

John Ryann picture John Ryann · Jun 9, 2011 · Viewed 7.1k times · Source

I can't seem to connect to my local database. Everytime I run it, it gives me a pop up blank windows (blank command line windows).

What do I miss?

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace dbtest1
{
    class Program
    {
        static void Main(string[] args)
        {
            string myConnectionString = "Initial Catalog=myDB;Data Source=localhost;Integrated Security=SSPI;";
            SqlConnection myConnection = new SqlConnection(myConnectionString);
            string myInsertQuery = "INSERT INTO tts (min, max, average, lh, stdev, main_id) Values(5,5,5,'ASU',5,55)";
            SqlCommand myCommand = new SqlCommand(myInsertQuery);
            myCommand.Connection = myConnection;
            myConnection.Open();
            myCommand.ExecuteNonQuery();
            myCommand.Connection.Close();
        }
    }
}

when I run debug it gives me error at myConnection.Open();

SqlException was unhandled: 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)

Answer

Colin Mackay picture Colin Mackay · Jun 9, 2011

Your SQL Server is not configured to talk over TCP/IP (which is what localhost implies)

You can either change your connection string to use (local) instead of localhost (note: the brackets are important.) Like this:

Data Source=(local);

or

you can configure your SQL Server to accept TCP/IP connections.

Open up SQL Server Confuguration Manager and Navigate to SQL Server Network Configuration --> Protocols for

On the right hand side you'll see a list of protocols such as Shared Memory, Named Pipes, TCP/IP etc. Ensure that TCP/IP is turned on. (Right-click and select "Enable")

You mention elsewhere you are using SQL Server Express, in which case your data source must also include the instance name SQLEXPRESS, like this:

Data Source=localhost\SQLEXPRESS