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';
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();
}
Some other problems with your query are that you are missing a space and the quotes go inside the string literal:
strOrdersSQL = strOrdersOrigSQL + " where FirstName = '"+ strFname + "'";
// ^ ^ ^
But this still won't work if the variable contains a quote character or backslash.
Instead of trying to escape the string you should use parameterized queries .
You dont need to worry about escaping charaters in Sql when passing from C#
Sql does it for you
all you need to do si:
string strOrdersOrigSQL = "SELECT LastName FROM Employees Where FirstName = @FirstName"
Nwo you can pass the value for @FirstName via SqlParameter this will protect you query from Sql injection
But it can be done as
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 + "'";
This is not proper way of doing it since it can be affected by SQL Injection. Use parameterised queries instead.
First of all, use SqlCommand. But if you choose to write direct SQL, it is OK as long as you escape your input. You should be very careful with this and know what you are doing. Else, your code presents an SQL Injection . Here is the correct code:
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.Replace("'", "''") + "'";
Assuming that strFname is a variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.