Escaping strings containing single quotes in PowerShell ready for SQL query

后端 未结 2 1569
情话喂你
情话喂你 2020-12-11 06:30

I am trying to run the following query, which takes someone\'s name and attempts to insert it into an SQL Server database table.

$name = \"Ronnie O\'Sullivan         


        
2条回答
  •  有刺的猬
    2020-12-11 06:46

    You can try to update your code to to use a parametrised value that will cope with quotes in a string:

    $query = "INSERT INTO People(name) VALUES(@name)"
    
    $command = $connection.CreateCommand()
    $command.CommandText = $query
    $command.Parameters.Add("@name", $name)  -- | Out-Null (may be required on the end)
    $command.ExecuteNonQuery()
    

    I'm not experienced with powershell but referenced this post for a parametrised query:

提交回复
热议问题