Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all single quotes with two single quotes in a string

Tags:

string

c#

I am trying to read value from DB using c#. The query string contains multiple single quotes - such as: Esca'pes' (the query strings are being read from a text file)

So, I wanted to replace all the single quotes with two single quotes before forming the SQL query. My code is as below:

if (name.Contains('\''))
{
    name = name.Replace('\'','\''');  
}

How to fix this?

like image 350
skjcyber Avatar asked Nov 28 '22 21:11

skjcyber


1 Answers

Use strings, not char literals.

name = name.Replace("'", "''");

However it sounds like you're concatenating SQL strings together. This is a huge "DO NOT" rule in modern application design because of the risk of SQL injection. Please use SQL parameters instead. Every modern DBMS platform supports them, including ADO.NET with SQL Server and MySQL, even Access supports them.

like image 161
Dai Avatar answered Dec 15 '22 06:12

Dai