2016-12-05 174 views
1

我創建了一個簡單的項目,以充分利用數據庫和表格。我用Menu->Project->Add New Item->Service-based Database a Users.mdf數據庫添加到項目中,其中我創建了表Users。我搜索了多個線程如何訪問數據庫,但目前爲止沒有任何工作。我的代碼現在看起來像這樣(我從YouTube教程中獲得了代碼),基本上當我點擊一個按鈕時,我預計會填充一個dataGridView從數據庫c獲取數據#

private void show_database_button_Click(object sender, EventArgs e) 
    { 
     string constring ="Server=(LocalDb)\v11.0;Database=Users.mdf;Trusted_Connection=true;MultipleActiveResultSets=true;"; 
     SqlConnection conDataBase = new SqlConnection(constring); 
     SqlCommand cmdDataBase = new SqlCommand(" select * from Users.Users;", conDataBase); 

     SqlDataAdapter sda = new SqlDataAdapter(); 
     sda.SelectCommand = cmdDataBase; 
     DataTable dbadataset = new DataTable(); 
     sda.Fill(dbadataset); 
     BindingSource bSource = new BindingSource(); 

     bSource.DataSource = dbadataset; 
     dataGridView1.DataSource = bSource; 
     sda.Update(dbadataset); 

    } 

當我按一下按鈕,我得到一個:

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)

我在做什麼錯在這裏? (需要提到的是我在代理連接上,不知道是否有什麼麻煩)。

+0

問題出在您的連接字符串。你能交叉檢查連接字符串嗎? –

+0

感謝您的建議@ un-lucky這是第一個問題,我使用'數據庫 - >(右鍵單擊)屬性 - >連接字符串(複製)'得到了連接字符串。現在我又遇到另一個錯誤:試圖爲文件附加一個自動命名的數據庫...' –

+0

並且不接受'User Interface = True' –

回答

0

A network-related or instance-specific error將在用戶未能對指定服務器進行身份驗證時發生。或者指定的服務器未找到或不可用。在你的情況下,請交叉檢查連接字符串以確認正確的身份驗證以及服務器。修復connectionString問題將解決您的問題。

-1

首先檢查連接字符串中是否正確提及了SQL SERVER實例名稱。如果不起作用,請嘗試重新啓動sql服務。 (它曾幫助我一次)

+0

你認爲這是一個答案嗎? – Badiparmagi

0

您的連接字符串不正確。

一個簡單的方法來建立一個連接蜇

  1. 創建一個新的文本文檔,並把它稱爲「connection.udl」(擴展名是重要的)
  2. 雙擊connection.udl文件
  3. 「數據鏈接屬性」對話框將打開。
  4. 填寫您要連接的數據庫的所有詳細信息。
  5. 通過單擊測試按鈕測試您是否正確。
  6. 打開connection.udl文件用記事本
  7. 第三線的連接字符串,這個複製並粘貼到你的代碼

注意您可能不得不如果你的文件的問題創建connection.udl文件如果是這樣的話,將explorer設置爲隱藏已知文件類型的擴展名。

+0

我找到的一個更簡單的方法是進入'Server Explorer',右鍵點擊數據庫,點擊'Properties'並且有一個字段'Connection String' :) –