我已经在网上浏览了一段时间并发现了许多类似的问题,但出于某种原因,我似乎无法使其正常工作。
我只是想连接到SQL服务器数据库并将查询结果输出到文件 - 请参阅下面的PowerShell脚本。我不确定的是如何将用户ID和密码集成到连接字符串中。
$SQLServer = "aaaa.database.windows.net"
$SQLDBName = "Database"
$uid ="john"
$pwd = "pwd123"
$SqlQuery = "SELECT * from table;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | out-file "C:\Scripts\xxxx.csv"
收到以下错误消息:
异常通话"填写"用" 1"参数:"此版本的SQL Server不支持Windows登录。"
答案 0 :(得分:25)
Integrated Security
和User ID
\ Password
身份验证是互斥的。要以运行代码的用户身份连接到SQL Server,请从连接字符串中删除User ID
和Password
:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
要连接特定凭据,请删除Integrated Security
:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
答案 1 :(得分:18)
在连接字符串中将Integrated security更改为false。
您可以通过使用您拥有的用户名/密码打开SQL管理工作室来检查/验证这一点,并查看是否可以从那里连接/打开数据库。注意!也可能是防火墙问题。
答案 2 :(得分:5)
# database Intraction
$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName;
User ID= YourUserID; Password= YourPassword"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
#End :database Intraction
clear
答案 3 :(得分:2)
假设您可以使用集成安全性,您可以删除用户ID并传递:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
答案 4 :(得分:1)
以下是窗口身份验证的答案
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"
答案 5 :(得分:0)
我确实删除了集成安全性……我的目标是使用带有活动目录用户名/密码的连接字符串登录到 sql 服务器。当我这样做时,它总是失败。格式无关紧要... sam company\user ... upn what@company.com ... 基本用户名。