簡體   English   中英

使用ExecuteNonQuery()的Powershell腳本拋出異常“'s'附近的語法不正確。”

[英]Powershell Script using ExecuteNonQuery() throws exception “Incorrect syntax near 's'.”

我編寫了一個非常簡單的腳本,它從文件和文件夾中收集數據,並將其上傳到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')"

這是輸出(我將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

無論您在“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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM