c# - 如何在 C# 应用程序上连接到 sql server

标签 c# sql sql-server winforms

我可以将 asp.net 应用程序连接到我在 SQL Server 2008 中的数据库,但是当我尝试在 Winforms 应用程序中从 Visual Studio 执行相同操作时,我总是会收到错误消息:

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)"

我使用连接字符串:

 SqlConnection Conn = new SqlConnection(@"Server=.\\myserver address\user;Database=testDatabase");

当我开始连接时加载表单时出现错误。

我已经转到我的 SQL Server 配置管理器,我得到了这个:

enter image description here

所以我不知道我做错了什么。程序文件中有旧版本 SQL Server 的先前文件,但我看不出它们会如何影响它...

我的sql服务

enter image description here

我还想补充一点,我已经将 sql server 添加到防火墙异常(exception)中

最佳答案

您应该考虑使用以下语法的连接

Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;Integrated Security=SSPI;

Server=myServerName\myInstanceName;Database=myDataBase;Integrated Security=true;

使用当前 Windows 帐户凭据时

或在 本地服务器 上使用默认 Windows 身份验证

Server=myServerName;Database=myDataBase;Integrated Security=true

(这是适用于 OP 的解决方案)

对于 @"Server=.\\myserver 在字符串前使用 @ 意味着没有字符会转义该字符串,所以

\\ 没有 @ 变成 \

\\@ 保持 \\

检查 C# '@' before a String

有关连接字符串的更多信息,请访问 connectionstrings.com

关于c# - 如何在 C# 应用程序上连接到 sql server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24115692/

相关文章:

sql - 如何比较同一表(SQL Server)中的2行?

sql-server - 处理 SQL 中字符串内的 IS NULL

c# - 绝对时间测量

c# - 在 Visual Studio 2010 中调试 Silverlight

c# - 在silverlight中从数据库中检索数据

c# - 我如何记录一个 c# dll

sql - 从表中删除重复记录 - SQL 查询

mysql - 使用 avg 的 where 子句子查询

父子排序的MySQL树

c# - 如何控制长时间运行的查询