【发布时间】:2019-04-10 11:04:08
【问题描述】:
我的 powershell 脚本有问题。我需要插入 mssql 数据库。
我明白了:
使用“0”参数调用“ExecuteNonQuery”的异常:“'00' 附近的语法不正确。” 在 C:\powershell\ImportPism.ps1:259 char:9 + $SqlCmd.ExecuteNonQuery() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SqlException
这是我的代码:
$sql = "
INSERT INTO [dbo].[akcja]
([ak_akt_id]
,[ak_sp_id]
,[ak_kolejnosc]
,[ak_interwal]
,[ak_zakonczono]
,[ak_sc_id]
,[ak_pr_id])
VALUES
(
$($item.akt_id)
,$($item.sp_id)
,0
,0
,$($item.data_dodania)
,NULL
,NULL)
select SCOPE_IDENTITY() as [InsertedId]
"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User Id=$login; Password=$password; Integrated Security = false";
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $sql
$SqlCmd.Connection = $sqlConnection
$SqlConnection.Open()
$InsertedId = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
为什么这不起作用?
【问题讨论】:
-
因为你的SQL在字符串替换后出现了语法错误,很明显。在没有看到结果的情况下,不可能准确地说出是什么。使用参数代替语句中的文本替换值。字符串替换看起来很方便,除非您遇到此类问题(或更糟糕的是,SQL 注入)。
-
谢谢@Jeroen Mostert。我使用参数并且没问题;)
标签: sql-server powershell