我創建了一個簡單的項目,以充分利用數據庫和表格。我用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)
我在做什麼錯在這裏? (需要提到的是我在代理連接上,不知道是否有什麼麻煩)。
問題出在您的連接字符串。你能交叉檢查連接字符串嗎? –
感謝您的建議@ un-lucky這是第一個問題,我使用'數據庫 - >(右鍵單擊)屬性 - >連接字符串(複製)'得到了連接字符串。現在我又遇到另一個錯誤:試圖爲文件附加一個自動命名的數據庫...' –
並且不接受'User Interface = True' –