I'm working on a web application which is vulnerable to SQL injection in its search box. It uses ASP.Net (C#) and Microsoft SQL Server.

In the search box it queries like:

Select Column1 from TBL where Column2 = N'  Here The Search box Content  ';

As you can see the above code is completely vulnerable to SQLi. What I did to mitigate this was just creating a method to replace all ' with '' which in SQL Server means it is a single quotation.

So if a user enters something like ' order by -- in the textbox the replace function will replace it with Replace("'","''"); and the SQL Server would never run the attacker's injected SQL.

So I just want to know that am I completely safe against SQLi? Or is there a way to bypass my injection protection?

  • 3
    You should just use prepared statements instead.
    – Anders
    Commented Jul 6, 2016 at 12:29
  • @Anders What do you mean by a prepared statement ? Regex ?! Commented Jul 6, 2016 at 12:31
  • 1
    No, not regex. Google it. Or read more about preventing SQLi in different languages here. (By the way, you do not specify what language the replace function is written in.)
    – Anders
    Commented Jul 6, 2016 at 12:33
  • @Anders I update my question , I use c#. well is it important what language I use ?! I think replace exist in all languages. Are they diffrent ?! Commented Jul 6, 2016 at 12:39
  • 2
    related: How to defeat doubling up apostrophes to create SQLi attack?
    – tim
    Commented Jul 6, 2016 at 12:43

1 Answer 1


No, that is not safe at all.

Replacing single-quotes with double-quotes or vice versa will only keep you safe from one type of injection. Also, what if the end user has a legitimate need to enter a single-quote mark?

As was pointed out in the comments, you should use Prepared Statements.

Below is an example, taken from the Microsoft documentation.

However, the technique is not unique to Microsoft. Every serious database supports prepared statements.

SqlCommand command = new SqlCommand(null, connection);

// Create and prepare an SQL statement.
command.CommandText =
    "INSERT INTO Region (RegionID, RegionDescription) " +
    "VALUES (@id, @desc)";
SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0);
SqlParameter descParam = 
        new SqlParameter("@desc", SqlDbType.Text, 100);
idParam.Value = 20;
descParam.Value = "First Region";

// Call Prepare after setting the Commandtext and Parameters.
  • Can you provide an example in which is not safe? I am not a security expert but can't find any. Also consider double quote is the way to escape single quote in string, so for string handling data are not lost. I ask this not because I advocate for this escaping technique but because some legacy code I work with use that mechanism and if broken I would like to know.
    – Skary
    Commented Feb 15, 2023 at 8:34

Not the answer you're looking for? Browse other questions tagged .