2015-11-19 45 views
0

我已經示例數據庫Northwind安裝和連接到C#項目錯誤連接到本地數據庫con.open()

我試圖連接到數據庫,並在數據庫中檢索表的列名,但我發現,而試圖打開連接,這裏的錯誤是我使用這樣做代碼:

public void connectToDB() 
{ 
    Dictionary<object, object> colns = new Dictionary<object, object>(); 
    List<string> colnNames = new List<string>(); 
    con = new SqlConnection("Data Source = .NorthwindDB.mdf; Integrated Security=True"); 
    con.Open(); 
    cmd = con.CreateCommand(); 
    cmd.CommandText = "SELECT * FROM Products"; 
    adapter = new SqlDataAdapter(cmd); 
    ds = new DataSet(); 
    adapter.Fill(ds); 
    dt = ds.Tables["Products"]; 
    foreach(DataRow dr in dt.Rows) 
    { 
     foreach(DataColumn dc in dr.Table.Columns) 
     { 
      colnNames.Add(dc.ColumnName.ToString()); 
     } 
    } 
    foreach(string key in colnNames) 
    { 
     Console.WriteLine(key.ToString()); 
    } 
    Console.ReadKey(); 
} 

,我發現了以下錯誤:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: 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)

另一件可能有用的事情,我注意到,只要點擊start按鈕執行代碼,數據連接NorthwindDB.mdf上出現的綠色插頭就會變成紅色x。

+0

'NorthwindDB.mdf'不是'Data Source'。 –

+0

你能解釋一下嗎?那它是什麼?我是新來的這種編程語言:) @ user2946329 –

+0

對不起delay @ user2946329,我已經找到了一種方法來從mdf文件的屬性面板中複製它,以獲得connectionString值,我只在內部添加了雙斜槓路徑字符串。無論如何非常感謝您的幫助和耐心。 –

回答

3

連接字符串是不正確,應該是這樣的:

con = new SqlConnection("Data Source=(local);" + 
         "Initial Catalog=NorthwindDB.mdf;Integrated Security=True"); 
// Or Data Source=.\\sqlexpress; 

您可以在此處詳細瞭解連接字符串:Database Connectionstrings