我发现了一些代码网上,但到目前为止,我无法得到它连接到我的SQL Server数据库。我按照这个网站的信:https://blogs.msdn.microsoft.com/walzenbach/2010/04/14/how-to-enable-remote-connections-in-sql-server-2008/
我已经允许远程连接,添加端口1433到我的防火墙等我再从运行PowerShell ISE中这样的代码:
$dataSource = “\\SCCM12-01\MSSQLSERVER”
$user = “MyID\OurDomain.org”
$pwd = “MyPassword”
$database = “CM1”
$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
当我运行此我得到以下错误。
异常调用“打开”和“0”的说法(S):建立SQL Server的连接“时出现与网络相关的或特定于实例的错误,服务器未找到或无法访问验证实例名称是否正确。和SQL Server配置为允许远程连接。(provider:SQL网络接口,错误:25 - 连接字符串无效)”
如果你有简单的查询做,我建议Select-SQLView PowerShell的模块。它可以快速选择从表或视图中的行。它存储你的数据库和服务器名称,以便您不必提供该值每一次。
像往常一样,你可以把结果表或GridView控件。
如果更复杂的查询,需要使用SQLCommands模块。
不知道为什么你收到此错误。您可以参考此链接https://github.com/Tervis-Tumbler/InvokeSQL
你可以试试这个单
function Invoke-SQL {
param(
[string] $dataSource = ".\SQLEXPRESS",
[string] $database = "MasterData",
[string] $sqlCommand = $(throw "Please specify a query.")
)
$connectionString = "Data Source=$dataSource; " +
"Integrated Security=SSPI; " +
"Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
}
错误消息实际上解释了什么是错的:
“SQL网络接口,error:25 - 连接字符串无效”。
有在连接字符串的东西不对劲。究竟是什么很难说,你掩盖大部分的细节。也许智能引号沉船的东西呢?也许你已经在密码一个引号字符?无论如何,这看起来你有invalid parameter用户ID:
$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”
尝试User Id
代替uid
像这样,
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
您正确只需要不使用数据库登录信息时需要改变“综合安全”为“真”
**Integrated Security=True**