Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape single quote in sql query c#

Tags:

c#

sql

sql-server

Here I have this method in my CandidateOp class file.

public SqlDataReader getpartyID(string partyName)
{
    string query = "EXEC partyIDtoInsert'" +partyName+ "'";
    return new DataAccessLayer().executeQuerys(query);
}

I'm passing the ComboBox text in the form and I am getting the ID to the integer type variable tempPrID.

SqlDataReader reader02 = new CandidateOP().getpartyID(cmbParty.Text);
if (reader02.HasRows)
{
    while (reader02.Read())
    {
         tempPrID = (Int32)reader02[0];
    }
    reader02.Close();
}
else
{
    MessageBox.Show("Please enter a valid Party Name", "Invalid DATA");
} 

The partyIDtoInsert, is a stored procedure I have created and it is being called in the method getpartyID as shown before, to get the id of united national party.

EXEC partyIDtoInsert 'United National Party'; 

If I have a party name called "United People's Freedom Alliance", so If I like to insert that name, my stored procedure executing code it looks like this.

EXEC partyIDtoInsert 'United People's Freedom Alliance';

In this case the it considers the end point as People's single quote and returns me with sql exception.

How to escape this single quote problem in the statement to execute my stored procedure.

like image 662
ChathurawinD Avatar asked Nov 28 '22 14:11

ChathurawinD


2 Answers

You should Use SqlParameters to avoid SQL Injection

string query = "EXEC partyIDtoInsert @PartyName";
Where you are executing the query

SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("@PartyName", partyName);

Otherwise, the problem is that you don't have " " between partyIDtoInsert and 'United People's Freedom Alliance'. If you want to continue using "EXEC partyIDtoInsert '" should be like this. But this is wrong! Read about SQL Injection!

like image 122
mybirthname Avatar answered Dec 13 '22 18:12

mybirthname


Just replace single quote (') by double single quote like ''.

so your function will look like:

public SqlDataReader getpartyID(string partyName)
            {
                string query = "EXEC partyIDtoInsert'" +partyName.Replace("'", "''") + "'";
                return new DataAccessLayer().executeQuerys(query);
             }

I hope it will solve your problem. :)

like image 24
Hitesh Avatar answered Dec 13 '22 18:12

Hitesh