2010-07-30 70 views
1

我想學習ADO.NET與SQL Server連接... 我安裝SQL Server與Visual Studio .... 有數據庫稱爲「Northwind」爲例它... 我想讀這個數據庫,我寫了這個代碼...異常與ADO.NET中的連接

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(); 
     } 
    } 
} 

當應用程序運行,這是需要一點時間再拋出異常,當它改掉打開連接... 例外的文字:

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)

我使用Windows 7作爲我的操作系統,我把用戶名在我的帳戶... 我相信,SQL服務器安裝在我的電腦 哪裏是我的錯誤上?

回答

3

要麼

  • 您還沒有SQL Server配置爲允許遠程連接,作爲錯誤信息告訴你=)
  • 你的數據源是錯誤的。嘗試.\SqlExpress或只需.通常,當Visual Studio安裝Sql Server Express時,它會將其安裝爲名爲SqlExpress的命名實例。
+0

謝謝...是的,我沒有配置Sql Server ... 當我這樣做,並把sqlexpress數據源文本.... 拋出一個新的例外... ((無法打開數據集「MyDataBase」請求登錄失敗登錄失敗用戶「Farah-PC/Farah」))。 – 2010-07-30 19:50:19

3

的Visual Studio包括Express版本的SQL Server。因此,您的連接字符串應該很可能看起來像"Data Source=(local)\sqlexpress;..."

0

如果你想快速嘗試不同的連接字符串&,我建議DatabaseTester(免責聲明 - 我寫了它)。它是免費的,並且是一種非常簡單的測試方法。此外,爲了搞清楚連接字符串ConnectionStrings.com是你最好的朋友。