SQL DB Power Shell连接代码错误我不明白

时间:2018-03-15 22:33:36

标签: sql database powershell syntax syntax-error

所以我有一些代码可以用来尝试写入数据库但是我一直在底部得到一个没有意义的错误。一切似乎都相互依赖,但执行代码只是......不。

我从中提取了这个db查询ps代码 https://blogs.msdn.microsoft.com/buckwoody/2009/04/13/run-a-sql-server-command-from-powershell-without-the-sql-server-provider/

这里是代码,错误在Close()下面。

我完全失败了。帮助

        $strserver = "1sl-den-db03"
$strdatabase = "reporting"
$strusername = "belamiinc\PSscripts"
#you can get convert pass by "p@ssw0rdt3xt" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Users\daniel.williams\Documents\Scriptcred.txt"
$strpassword = Get-Content "C:\Users\daniel.williams\Documents\Scriptcred.txt" | ConvertTo-SecureString
#$strQuery = "
#INSERT INTO EventLog (SourceID, Started, Completed, Result, Context, Machine)
#SELECT (50, null, null, 'error undefined query','query run outside of manufacturer','1sl-den-db03')
#"
$strQuery = "
insert into [reporting].[dbo].[password] (Username, Password)
select (test, testpw)
"


# Create and open a database connection
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=$strserver;database=$strdatabase;Integrated Security=SSPI; User ID=$strusername; password=$strpassword"


#Create a command object
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = $strQuery

$sqlConnection.Open()

#Execute the Command
$sqlCommand.ExecuteNonQuery()

$sqlConnection.Close()

错误是:

PS C:\Windows> Y:\DEPT - IT\Scripting\PSConnecttoSQL.ps1
Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near ','."
At Y:\DEPT - IT\Scripting\PSConnecttoSQL.ps1:27 char:1
+ $sqlCommand.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException

1 个答案:

答案 0 :(得分:0)

您不需要读者才能获得INSERT命令。改变这一行:

 $sqlReader = $sqlCommand.ExecuteReader()

分为:

 $sqlCommand.ExecuteNonQuery()

有关SqlCommand.ExecuteNonQuery()

的更多信息