通过 PowerShell 连接到本地 SQL Server 数据库失败,错误:命名管道提供程序,错误:40

通过 PowerShell 连接到本地 SQL Server 数据库失败,错误:命名管道提供程序,错误:40

请告诉我为什么这个连接失败...我该怎么办?

  • 本地机器名称 =MYPC
  • 本地实例名称 =MSSQLSERVER
  • 我自己的数据库名为mydatabase
  • 我使用 Windows 身份验证登录本地服务器,用户名 =DOMAIN\mypc
  • 我登录本地服务器的时候没有密码;

我使用的行如下:

$connection= new-object system.data.sqlclient.sqlconnection
$connection
$Connection.ConnectionString ="server=MSSQLSERVER;database=mydatabase;trusted_connection=false;uid=DOMAIN\mypc;"
$Connection.ConnectionString
$connection.open()

这些行失败并出现以下错误:

Exception calling "Open" with "0" argument(s): "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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
At line:1 char:17
+ $connection.open <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

答案1

我们的连接字符串存在一些问题:

MSSQLSERVER 通常是 SQL Server 默认实例的服务名称,在这种情况下,您可以使用“server=MYPC”,或者您可以使用点表示本地计算机“server=.”。如果您确实有一个 MSSQLServer 实例名称(这值得怀疑),那么您的服务器名称将是“server=.\MSSQLSERVER”

当使用 Windows 身份验证(即 trust_connection)时,您无需指定 uid,并且 trust_connection 应设置为 true。您的连接应如下所示:

$Connection.ConnectionString ="server=.;database=mydatabase;trusted_connection=true;"

相关内容