Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape Character for SQL in C#

Tags:

c#

.net

I want to add a simple select statement in my C# code. Sample looks like below. The value like y in fname comes from a parameter. //select lname from myTable where fname = 'y'

Here's what I m doing. I m obviously getting Sql Exception. How do I correct it? Thanks.

string strOrdersOrigSQL = "SELECT LastName FROM Employees";
// Concatenate the default SQL statement with the "Where" clause and add an OrderBy clause
       strOrdersSQL = strOrdersOrigSQL + "where FirstName ="+ 'strFname';
like image 305
Nemo Avatar asked May 27 '26 14:05

Nemo


1 Answers

You should never concat sql commands by hand. Use the class SqlCommand and add parameters

using (var cmd = new SqlCommand("SELECT LastName FROM Employees where FirstName = @firstName", conn))
{
   cmd.Parameters.AddWithValue("@firstName", strFname);
   var reader = cmd.ExecuteReader();
}
like image 189
Oskar Kjellin Avatar answered May 30 '26 05:05

Oskar Kjellin