简体   繁体   中英

Exception with connection in ADO.NET

I am trying to learn ADO.NET to connect with SQL Server ... I install SQL Server with Visual Studio .... there is data base called "Northwind" as example with it ... I am trying to read this database , I wrote this code ...

using System;
using System.Data;
using System.Data.SqlClient;

namespace DataSetReaderFromSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection connection = new SqlConnection(@"Data Source=(local);Integrated Security=SSPI;" + "Initial Catalog=Northwind");
            connection.Open();
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "Select CustomerID , CompanyName from Customers";
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
                Console.WriteLine(reader["CustomerID"] +""+ reader["CompanyName"]);
            reader.Close();
            connection.Close(); 
        }
    }
}

When the application runs, it's take a little of time then throw exception when it trys to open connection ... the text of the exception :

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 am using Windows 7 as my operating system, and I put username on my account ... I am sure that SQL Server was installed on my computer where is my error ??

Visual Studio includes Express edition of SQL Server. Thus, your connection string should most likely look like "Data Source=(local)\\sqlexpress;..." .

Either

  • You haven't configured Sql Server to allow remote connections, as the error message tells you =)
  • Your datasource is wrong. Try .\\SqlExpress or just . Ordinarily when Visual Studio installs Sql Server Express, it installs it as a named instance called SqlExpress.

If you want a quick & easy way to try different connection strings, I suggest DatabaseTester (disclaimer - I wrote it). It's free and a very easy way to test. Also, for figuring out connections strings ConnectionStrings.com is your best friend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM