using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SQLSingleQuotes
{
class Program
{
static void Main(string[] args)
{
ReplaceString obj = new
ReplaceString();
obj.MY_Method();
}
}
class ReplaceString
{
public void
MY_Method()
{
string FirstName = "John";
string LastName = "O'Conner";
string UserName = "joconner";
string Email = "joconner@domain.tld";
// Both these queries are broken because of the space.
string strQuery1 = "SELECT
* FROM User WHERE LastName='" + LastName + "'";
string strQuery2 = "INSERT
INTO User (FirstName, LastName, UserName, Email) VALUES (" +
"'" + FirstName + "',"
+
"'" + LastName + "',"
+
"'" + UserName + "',"
+
"'" + Email + "')";
// This will
actually break your query too, because it will replace valid single quotes
// with two single quotes.
You need to do this on the actually data strings.
strQuery1 = strQuery1.Replace("'",
"''"); //
strQuery2 = strQuery1.Replace("'",
"''");
// Replace any intance of a single quote with two single
quotes, ''.
// IMPORTANT: Typing two single quotes ('') is not the same
as a double quote (").
FirstName = FirstName.Replace("'",
"''");
LastName = LastName.Replace("'",
"''");
UserName = UserName.Replace("'",
"''");
Email = Email.Replace("'", "''");
// Both these queries are working now;
strQuery1 = "SELECT * FROM User WHERE
LastName='" + LastName + "'";
strQuery2 = "INSERT INTO User
(FirstName, LastName, UserName, Email) VALUES (" +
"'" + FirstName + "',"
+
"'" + LastName + "',"
+
"'" + UserName + "',"
+
"'" + Email + "')";
}
}