我创建了一个简单的项目,以充分利用数据库和表格。我用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' –