我試圖運行以下查詢,該查詢需要某人的名字並試圖將其插入到SQL Server數據庫表中。轉義在PowerShell中包含單引號的字符串準備SQL查詢
$name = "Ronnie O'Sullivan"
$dataSource = "127.0.0.1"
$database = "Danny"
$connectionString = "Server=$dataSource;Database=$database;Integrated Security=True;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = "INSERT INTO People(name) VALUES('$name')"
$command = $connection.CreateCommand()
$command.CommandText = $query
$command.ExecuteNonQuery()
$connection.Close()
我面臨的問題是單引號引起我的查詢中的問題。該查詢正在執行爲
INSERT INTO People(name) VALUES('Ronnie O'Sullivan')
這會導致SQL語法錯誤。
我的問題是我如何轉義我的$ name變量,以便它在SQL端呈現。
一種解決方法是做一個查找和我的名字$變量替換,發現:'替換:‘’
$name.Replace("'", "''")
是否有一個更優雅的解決方案在那裏,或者一個功能,我不能似乎找到?
謝謝。
你不能在查詢中使用quotename嗎? I.e .:插入人員(姓名)VALUES(QUOTENAME($姓名)) –