从PowerShell连接到SQL Server数据库

iq3niunx  于 2022-11-28  发布在  Shell
关注(0)|答案(8)|浏览(226)

我已经在网上找了一段时间了,发现了许多类似的问题,但由于某种原因,我似乎不能得到这个工作。
我只是尝试连接到SQL Server数据库并将查询结果输出到文件-请参阅下面的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”个参数调用“Fill”时发生异常:“此版本的SQL Server不支援Windows登入。”

ohtdti5x

ohtdti5x1#

Integrated SecurityUser ID \ Password验证是互斥的。若要以执行程式码的使用者身份连接到SQL Server,请从连接字串中移除User IDPassword

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"

要使用特定凭据进行连接,请删除Integrated Security

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
brjng4g3

brjng4g32#

在连接字符串中将Integrated security更改为false。
您可以使用您拥有的用户名/密码打开SQL Management Studio来检查/验证这一点,并查看是否可以从那里连接/打开数据库。注意!也可能是防火墙问题。

sauutmhj

sauutmhj3#

# 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
vktxenjb

vktxenjb4#

Windows身份验证的答案如下

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"
mu0hgdu0

mu0hgdu05#

假设您 * 可以 * 使用集成安全性,则可以删除用户ID并传递:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
pepwfjgg

pepwfjgg6#

要以活动目录用户身份连接到SQL Server,只需以活动目录用户身份启动PowerShell,然后使用TrustedSecurity=true连接到SQL Server

bq3bfh9z

bq3bfh9z7#

我确实删除了集成安全性...我的目标是使用带有Active Directory用户名/密码的连接字符串登录到sql服务器。当我这样做时,它总是失败。格式无关紧要... sam company\user... upn whatever@company.com...基本用户名。

368yc8dk

368yc8dk8#

我认为,只有在SQL Server数据库上明确设置特定用户使用密码登录(即,不从集成的Windows /单点登录继承凭据)时,这种方法才有效

相关问题