6

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"

$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()

The problem I am facing is that the single quote is causing an issue in my query. The query is being executed as

INSERT INTO People(name) VALUES('Ronnie O'Sullivan')

which causes an SQL syntax error.

My question is how do I escape my $name variable so that it renders on the SQL side.

One solution is to do a find and replace on my $name variable, find: ' replace: ''

$name.Replace("'", "''")

Is there a more elegant solution out there, or a function that I can't seem to find?

Thank you.

Danny Cullen
  • 1,714
  • 4
  • 29
  • 46

2 Answers2

17

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:

Tanner
  • 21,369
  • 9
  • 63
  • 79
1

Tanner's helpful answer is definitely the most robust and secure solution, because using a [parameterized / prepared statement (query) eliminates any possibility of a SQL injection attack.

However, in this constrained case, where you want to insert a value into a single-quoted SQL string ('...'), you can get away with simply doubling any embedded ' characters in the value:

$query = "INSERT INTO People(name) VALUES('$($name -replace "'", "''")')"

The above uses PowerShell's string interpolation via $(...), the subexpression operator, to embed an expression that uses the -replace operator to double all embedded ' instances in the value of $name.

Note: You could also use $name.Replace("'", "''") above, which performs better in this simple case, but PowerShell's -replace operator is generally preferable, not only for being PowerShell-native, but for offering superior abilities, because it is regex-based and supports array as its LHS - see this comment on GitHub.

mklement0
  • 312,089
  • 56
  • 508
  • 622