简体   繁体   English

如何在C#应用程序上连接到SQL Server

[英]How to connect to sql server on c# application

I can connect asp.net applications to my databases in SQL Server 2008, however when I try to do the same from Visual Studio in a Winforms application, I always get the error: 我可以将asp.net应用程序连接到SQL Server 2008中的数据库,但是当我尝试从Winforms应用程序中的Visual Studio中执行相同操作时,总是会收到错误消息:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. 建立与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. 验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)" (提供者:SQL网络接口,错误:26-指定服务器/实例时出错)

I use the connection string: 我使用连接字符串:

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

and I get an error when my form loads as that is when I start the connect. 当我的表单加载时出现错误,即当我启动连接时。

I have gone to my SQL Server Configuration Manager and I get this: 我去了我的SQL Server配置管理器,我得到了:

在此处输入图片说明

So I do not know what I am doing wrong. 所以我不知道我在做什么错。 There are previous files for older versions of SQL Server in the program files however I do not see how they could affect it... 程序文件中有旧版本的SQL Server的以前的文件,但是我看不到它们如何影响它...

My sql services 我的SQL服务

在此处输入图片说明

I would also like to add that I added sql server to the firewall exceptions already 我还想补充一点,我已经将sql server添加到了防火墙例外中

You should consider using connection with following syntax 您应该考虑使用具有以下语法的连接

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

OR 要么

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

When using current Windows account credentials 使用当前的Windows帐户凭据时

OR on local Server with default Windows authentication 或在具有默认Windows authentication local Server

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

(this was solution that worked for OP) (这是适用于OP的解决方案)

And for @"Server=.\\\\myserver using @ before string means that no character would escape that string so 对于@"Server=.\\\\myserver在字符串前使用@表示没有字符会转义该字符串,因此

\\\\ without @ turns into \\ 没有@ \\\\变成\\

\\\\ with @ stays \\\\ \\\\@停留\\\\

check C# '@' before a String 在字符串前检查C#'@'

For more information about connection strings please visit connectionstrings.com 有关连接字符串的更多信息,请访问connectionstrings.com

Check whether these services has been started or not as shown in below snapshot 检查这些服务是否已启动,如下快照所示

在此处输入图片说明 .. ..

If then try to start them and please try to connect your database. 如果然后尝试启动它们,请尝试连接数据库。

请尝试使用以下命令:我发现您的MOF可能有问题。

mofcomp.exe "C:\Program Files (x86)\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM