【问题标题】:Connect to SQL Server using C# code fails使用 C# 代码连接到 SQL Server 失败
【发布时间】:2013-05-12 14:11:02
【问题描述】:

SqlConnection 在使用命名实例安装 SQL Server 的 Windows 2008 R2 独立环境中失败:

        SqlConnection myConnection = new SqlConnection(
            "user id=domain/username;password=pa$$word;server=MyServername/MyInstanceName;" +
            "Trusted_Connection=yes;database=MyDatabase2;connection timeout=30");

我可以使用 Visual Studio 的“服务器资源管理器”成功连接到 SQL Server 实例它创建的连接字符串是:

Data Source= MyServername\MyInstanceName;Initial Catalog=MyDatabase2;Integrated Security=True

在我的 SqlConnection 中,我尝试了以下结果...

server=MyServername/MyInstanceName;" +    //fails within timeout
server=MyServername\MyInstanceName;" +    //Unrecognized escape sequence
server=MyServername\\MyInstanceName;" +   //suspends far longer than timeout
server=localhost\\MyInstanceName;" +      //suspends far longer than timeout
server=localhost/MyInstanceName;" +       //fails within timeout

这不是远程连接。 VS 和 SQL Server 都在同一台机器上。如何连接到命名实例?

这是我收到的错误消息:

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-s
pecific 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 a
nd that SQL Server is configured to allow remote connections. (provider: Named P
ipes Provider, error: 40 - Could not open a connection to SQL Server) ---> Syste
m.ComponentModel.Win32Exception (0x80004005): The network name cannot be found
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception
, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObj
ect stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternal
ConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Bool
ean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFa
ilover)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSn
iOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirect
edUserInstance, SqlConnectionString connectionOptions, SqlCredential credential,
 TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTime
r timeout, SqlConnectionString connectionOptions, SqlCredential credential, Stri
ng newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdent
ity identity, SqlConnectionString connectionOptions, SqlCredential credential, O
bject providerInfo, String newPassword, SecureString newSecurePassword, Boolean
redirectedUserInstance, SqlConnectionString userConnectionOptions)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOp
tions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConn
ectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)

   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConn
ectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbCon
nectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions
 userOptions)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOp
tions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection ow
ningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean o
nlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& co
nnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection ow
ningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbCon
nectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
 owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions
, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
 outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1
retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at ConsoleApplication1.Program.Main(String[] args) in c:\Users\hptSetupAdmin\
Documents\Visual Studio 2012\Projects\ConsoleApplication1_ConnToSql\ConsoleAppli
cation1\Program.cs:line 33
ClientConnectionId:00000000-0000-0000-0000-000000000000

谢谢!

【问题讨论】:

  • 您的应用程序在什么凭据(Windows 用户)下运行?
  • 尝试使用服务器资源管理器使用您在应用程序中提供的连接字符串参数进行连接
  • 嗯.. 我不知道您可以使用域登录名和密码进行连接 - 我一直认为您需要一个受信任的连接。我可能是错的。假设这是一种合法的连接方式,您应该尝试在连接字符串用户 ID 中使用反斜杠而不是正斜杠:...("user id=domain\username...
  • 以管理员身份运行visual studio并重试
  • 尝试从连接字符串中删除受信任的连接部分。 "数据源=myServerAddress;初始目录=myDataBase;集成安全=SSPI;"

标签: c# sql-server


【解决方案1】:

对于本地实例,最好使用“。”而不是服务器名称。例如:

string constr="server=.\<instance-name>;integrated security=true;database=<db-name>";

检查这是否有效。

【讨论】:

  • 谢谢阿米特,它现在正在工作。 (错误是我的,请参阅我上面的评论。)我会给你这个,因为很高兴知道我可以使用“。”而不是服务器名称。 BTW server=.\&lt;instance-name&gt; 导致“无法识别的转义序列”,但 server=.\\&lt;instance-name&gt; 有效。也许“\”是 C# 的转义序列。感谢您的回复。
  • 是的,反斜杠是 C# 中的一个转义序列,它在字符串中赋予特殊含义,例如 \n 表示换行符等。这就是为什么我们必须在我们想要使用的情况下使用双反斜杠c# 字符串中的单个反斜杠。对于上述连接字符串中的单个反斜杠造成的混乱,我深表歉意。
【解决方案2】:

如果你想通过用户/密码而不是使用集成安全连接到 sql-server

  • 您的用户需要访问服务器所在的 Windows 机器的访问权限
  • 您的数据库必须配置为接受通过用户/密码登录
  • 您必须授予此用户对 sql-server 和您要使用的数据库的访问权限。

您的代码是否在网络应用程序中运行?如果是这样,iis-default-user 可能没有对运行服务器的 windows 机器的访问权限

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2015-06-02
    • 2013-11-02
    相关资源
    最近更新 更多