使用ExecuteNonQuery()的Powershell脚本抛出异常"'s'附近的语法不正确."

Mat*_*rne 6 sql powershell

我编写了一个非常简单的脚本,它从文件和文件夹中收集数据,并将其上传到SQL数据库.我相信我的问题与参数化sql的问题有关,但我不明白为什么或为什么.

我认为我需要做的是重新格式化sql字符串以防止某些字符进入.

任何帮助赞赏.

这是代码:

$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $dbConnection
$Command.CommandText = "INSERT INTO FileSizeTable (FileName,FileSize,FileNameLength,Date) VALUES ('$i','$items','$temp','$currentDate')" 

$Command.ExecuteNonQuery()

"INSERT INTO FileSizeTable (FileName,FileSize,FileNameLength,Date) VALUES ('$i','$items','$temp','$currentDate')"
Run Code Online (Sandbox Code Playgroud)

这是输出(我将sql命令字符串作为测试推出):

INSERT INTO FileSizeTable (FileName,FileSize,FileNameLength,Date) VALUES ('ATI Te
chnologies','61.16 MB','39','05/24/2013 21:05:56')
ATI Technologies            61.16 MB                                           39
1
INSERT INTO FileSizeTable (FileName,FileSize,FileNameLength,Date) VALUES ('ATIToo
l','0.00 MB','30','05/24/2013 21:05:56')
ATITool                     0.00 MB                                            30
1
INSERT INTO FileSizeTable (FileName,FileSize,FileNameLength,Date) VALUES ('Auran'
,'7,496.04 MB','28','05/24/2013 21:05:56')
Auran                       7,496.04 MB                                        28
Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near 
's'.
Unclosed quotation mark after the character string ')'."
At line:143 char:25
+                         $Command.ExecuteNonQuery()
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Run Code Online (Sandbox Code Playgroud)

alr*_*roc 8

无论您在"Auran"记录之后尝试插入哪些数据,其中都有单引号/撇号.当您使用字符串连接来构造查询时,这是一个巨大的风险,并使您开始接受SQL注入攻击.

将您正在构建的字符串粘贴到SSMS或其他可以为您提供SQL语法突出显示的工具中,您将看到它.

您在Coding Horror上找到的帖子提供了正确的建议/答案 - 使用参数化查询,这就消失了.出于性能和安全原因,目前通常不鼓励SQL语句的字符串连接.更不用说作为源代码更容易阅读.

$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $dbConnection
$Command.CommandText = "INSERT INTO FileSizeTable (FileName,FileSize,FileNameLength,Date) VALUES (@name,@size,@length,@dt)";
$Command.Parameters.Add("@name", $i);
$Command.Parameters.Add("@size", $items);
$Command.Parameters.Add("@length", $temp);
$Command.Parameters.Add("@dt", $currentdate);
$Command.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)