[英]How to automatically attach SQL Server database in C#?
我是 C# 和 SQL Server 2014 Express 的新手,我正在使用 Windows 表单。
我正在构建从/向 SQL Server 数据库读取/写入的小型应用程序。 我正在尝试自动附加 SQL Server 数据库,然后从名为Test_Table
的表中读取数据,然后填充Datagridview
。
我使用的代码:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand= new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter= new SqlDataAdapter();
private void button1_Click(object sender, EventArgs e)
{
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM Test_Table ";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
dataGridView1.DataSource = DataTable;
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
应用程序配置:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=localhost; AttachDbFilename=D:\\DB\\MyDB.mdf;Integrated Security=True"/>
</connectionStrings>
当我单击button1
它会引发错误:
尝试为文件 D:\\DB\\MyDB.mdf 附加自动命名的数据库失败。 存在同名数据库,或无法打开指定文件,或位于 UNC 共享上。
我没有附加其他数据库并且数据库路径是正确的。 我看过here , here和here,但没有一个有帮助。
知道如何自动附加 SQL Server 数据库文件吗? 谢谢
您使用的是什么版本的 SQL Server? 这将解释很多有关您的错误消息的信息。
您的连接字符串:
“数据源=本地主机;AttachDbFilename=D:\\DB\\MyDB.mdf;集成安全性=True”
您只能将 AttachDbFilename 与 SQL Express 一起使用。 在您的连接字符串中,数据源设置为localhost 。 这听起来像您安装了完整版本的 SQL Server。
如果您安装了完整版的 SQL Server,则只能通过 Management Studio 附加数据库。
如果您使用的是 SQL Express,请更改您的数据源:
Data Source=.\SQLEXPRESS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.