开发者

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 ??


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.


Visual Studio includes Express edition of SQL Server. Thus, your connection string should most likely look like "Data Source=(local)\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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜