【问题标题】:Exception calling "ExecuteNonQuery" with "0" argument(s)使用“0”参数调用“ExecuteNonQuery”的异常
【发布时间】: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


【解决方案1】:

当我没有将日期时间参数括在单引号中时出现此错误。

例如确保在 string.format 中添加引号

String.Format("插入 [dbo].tbl 值 ({0})

插入 [dbo].tbl 值 (0001-01-01 00:00:00.000)

需要:

String.Format("INSERT INTO [dbo].tbl VALUES ('{0}')

插入 [dbo].tbl 值 ('0001-01-01 00:00:00.000')

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多