使用 PowerShell 连接到 SQL Server localdb

问题描述 投票:0回答:1

我编写了一个 PowerShell 脚本来连接到 SQL Server localdb。

$connection = New-Object System.Data.SqlClient.SqlConnection;
$connection.ConnectionString = "Data Source=(localdb)\mssqllocaldb; Initial Catalog=master; Persist Security Info=True; Integrated Security=False; User ID=sa; Password=123; MultipleActiveResultSets=true; TrustServerCertificate=True;";
$connection.Open();

连接不起作用并显示以下错误:

(提供者:SQL Network Interfaces,错误:26 - 错误定位 指定服务器/实例)

我在 .NET 8 中使用了相同的代码并且连接有效:

var connection = new System.Data.SqlClient.SqlConnection();

connection.ConnectionString = "Data Source=(localdb)\\mssqllocaldb; Initial Catalog=master; Persist Security Info=True; Integrated Security=False; User ID=sa; Password=123; MultipleActiveResultSets=true; TrustServerCertificate=True;";
connection.Open();

PowerShell 脚本中是否缺少某些内容?

c# sql-server powershell .net-8.0 localdb
1个回答
0
投票

我有一个用于测试 asp.net core 身份的本地数据库,然后我使用下面的 powershell 脚本进行了测试,它对我有用。

$connectionString = "Server=(localdb)\mssqllocaldb;Database={Database_Name};Trusted_Connection=True;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()


$query = "SELECT * FROM dbo.AspNetUsers"
$command = $connection.CreateCommand()
$command.CommandText = $query

$adapter = New-Object System.Data.SqlClient.SqlDataAdapter
$adapter.SelectCommand = $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataset)
$dataset.Tables[0] | Format-Table -AutoSize

$connection.Close()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.