ADO.NET:无法连接到 mdf 数据库文件
我正在编写一个使用 SQL Server 2005 数据库的应用程序。在连接字符串中,我指定 mdf 文件,如下所示:
connstr = @"Data Source=.\SQLEXPRESS; AttachDbFilename=" + fileLocation + "; Integrated Security=True; User Instance=True";
当我执行代码时:
public static void forceConnection()
{
try
{
conn = new SqlConnection(connstr);
conn.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if(conn != null)
conn.Close();
}
}
我收到异常:
建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。找不到服务器或无法访问服务器。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供程序:SQL 网络接口,错误:26 - 定位指定的服务器/实例时出错)
此代码适用于 XP,但不适用于 Vista。我尝试在管理模式下运行 Visual Studio 并将 mdf 文件移至“用户数据”文件夹,但错误仍然存在。
有什么帮助吗?
I'm writing an application that uses a SQL Server 2005 database. In the connection string I'm specifying the mdf file like this:
connstr = @"Data Source=.\SQLEXPRESS; AttachDbFilename=" + fileLocation + "; Integrated Security=True; User Instance=True";
When I execute the code:
public static void forceConnection()
{
try
{
conn = new SqlConnection(connstr);
conn.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if(conn != null)
conn.Close();
}
}
I receive an exception:
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
This code works on XP but not in Vista. I tried to run Visual Studio in admin mode and moved the mdf file to "user data" folders but the error persists.
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在命令提示符中连接到 sql server 数据库吗?我会先确保您确实可以连接。
尝试打开 cmd 提示符并输入
sqlcmd -S .\SQLEXPRESS -d your_dbase
Can you connect to the sql server db in your command prompt? I would make sure you can actually connect first.
Try open the cmd prompt and type
sqlcmd -S .\SQLEXPRESS -d your_dbase
如果我的 dotnet-sourcecode 出现 mssql-connect 问题,我会尝试使用不同的程序连接到数据库。我使用也是用 dotnet 编写的 queryexpress 。如果这个程序有效,那么我就知道问题出在我的程序代码上,否则问题出在连接字符串、代理、网络、sqlserver 或用户权限上。
If I have mssql-connect problems with my dotnet-sourcecode I try to connect to the database with a different program. I use queryexpress that is also written in dotnet. If this program works then I know that the problem is with my program code else the problem is with connection string, proxy, network, sqlserver or user permissions.
你真的安装了sqlexpress吗?它是使用 machineName\sqlexpress 还是作为默认实例运行?
你必须核实这些情况。
如果您不使用默认实例,您可能想使用实际的 machineName\instance 名称。
Do you actually have sqlexpress installed? does it use the machineName\sqlexpress or does it run as a default instance?
You have to verify these cases.
and you might wanna use the actual machineName\instance name if you aren't using the default instance.