Escape Character for SQL in C# - c#

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();
}

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

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.

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.

Related

sql delete query with "%" operator in c#

i'm trying to delete a row giving a value of a column, but it only deletes when i give the full value (i.e name column = sam jack) then to delete it i have to input sam jack.
so i'm trying to use the % operator but don't know how to put it in the query.
here is my code :
command.CommandText = "DELETE FROM dbo.workers WHERE Name like #name" + "%";
You are doing it wrong.
Use parameterized queries also.
command.CommandText = "DELETE FROM dbo.workers WHERE Name like #name";
command.Parameters.AddWithValue("#name","%" + searchString + "%");
Or if you want to delete only starts with your string, don't use first % like;
command.Parameters.AddWithValue("#name", searchString + "%");
You can either concatenate % and the parameter value in the host language, or you can do it in SQL:
command.CommandText = "DELETE FROM dbo.workers WHERE Name like #name+'%'";
In SQL Server 2012 you can use CONCAT to be more explicit:
command.CommandText = "DELETE FROM dbo.workers WHERE Name like CONCAT(#name, '%')";

Unable to do a query using a textbox input

I am trying to allow user to enter details inside a textbox and use that information to run a SQL query. It works when I hard code everything for example:
string query = "SELECT * FROM PERSONS WHERE Name='Samuel'";
When I try to use the textbox instead as follows, it returns an error. I am definitely entering the correct name Samuel in the textbox. I ran a messagebox to check if the textbox is registering the name correctly and yes, it is correct. Please advice if you see anything wrong. Thanks.
name = textbox4.Text;
MessageBox.Show(name);
string query = "SELECT * FROM PERSONS WHERE Name=" + name;
What language? C#?
string query = string.Format("SELECT * FROM PERSONS WHERE Name = '{0}'", SanitizeSql(name));
Or you could be cool and use https://github.com/markrendle/Simple.Data then it would just be
IEnumerable<Person> people = db.Persons.FindAllByName(name);
and this also takes care of SQL injection and is database independent (so you can switch from MSSQL to MySQL to MongoDB...)
You forgot quotes. Change query like below:
string query = "SELECT * FROM PERSONS WHERE Name='" + name + "'";
string query = "SELECT * FROM PERSONS WHERE Name=" + name;
Should be
string query = "Select * From PERSONS Where name = '" + name + "'" ;
Use name=txbox.Text;
dbLog.Open("SELECT * FROM Persons WHERE Name='" & name & "'", dbCon, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)

How to use MySql select with c#

Can anyone tell whats wrong with my code? I have tried a million different things and I cant seem to make it work. I need to make a select in my mysql database and use the id from the table with the specified name I take from a combobox.
I took that name from the combobox and put it into a variable named "nomeres", now I need to do a select with it and take the id from that name from the database. Everything I try to do results in a mysql syntax error in line 1, but I've tried alot of things and its always the same. The database is fine, I tried the select directly from it myself, no tables or columns names are incorrect. This is the code im using:
MySql.Data.MySqlClient.MySqlConnection dbConn = new MySql.Data.MySqlClient.MySqlConnection("Persist Security Info=False;server=localhost;database=notas;uid=root;password=" + dbpwd);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres;
try
{
dbConn.Open();
} catch (Exception erro) {
MessageBox.Show("Erro" + erro);
this.Close();
}
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
idnumber = reader.ToString();
}
as others have already pointed you towards right direction,
i would like to suggest you to use parameterised queries to avoid SQL injection attacks.
Your query is open to SQL injection attacks so please read here
Try This: using parameterised SQL queries
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValue("#nome",nomeres);
You need to terminate the string in the query:
"SELECT id from residentes WHERE nome ='" + nomeres + "'"
In general, when trying to debug this type of code, it helps to print out the query string after all substitutions have been made.
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres + "';";
actually you misses the semicolon of the query that have to enter within the quotes. and the second semicolon is for the end of statement.
But I preffer wo write commands like
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValues("#nome", variableName);
then execute the query and retrieve your results.
Missing single quote:
"SELECT id from residentes WHERE nome ='" + nomeres + "'";
^

SQL parameterized query not showing result

I have following function in my DataAcess class, but it is not showing any result.
My code is as follow:
public List<Products> GetProduct(string productName)
{
System.Data.DataSet ds = null;
db = DBWrapper.GetSqlClientWrapper();
db.ClearParameters();
db.AddParameter(db.MakeInParam("#ProductName", DbType.String, 30, productName));
string query = #"SELECT ProductId
FROM [Products]
WHERE Name LIKE '%#ProductName%'";
ds = db.GetDataSet(query);
db.ClearParameters();
// Rest of Code
}
I also tried:
string query = #"SELECT ProductId
FROM [Products]
WHERE Name LIKE '%"+"#ProductName"+"%'";
But it runs fine without parameterized like:
string query = #"SELECT ProductId
FROM [Products]
WHERE Name LIKE '%"+productName+"%'";
How to write this with parameterized using #ProductName???
You should use
LIKE '%' + #ProductName + '%'
instead of
LIKE '%#ProductName%'
Why? Because in query, your parameter is inside quotes. In quotes, SQL will recognize it as a string literal and never sees it as a parameter.
As an alternative, you can use your % % part in your AddParameter method as
Damien_The_Unbeliever mentioned.
Try, instead:
db.AddParameter(db.MakeInParam("#ProductName", DbType.String, 30, "%" + productName + "%"));
string query = #"SELECT ProductId
FROM [Products]
WHERE Name LIKE #ProductName";
SQL doesn't look for parameters inside of literal strings. So you can make the parameter be the entire string argument for the LIKE operator.
Rather than adding a parameter, you can also use:
string query = String.Format("Select ProductId FROM Products where Name LIKE '{0}'", productName);

In C# how to get value from text box using quotes

In my program i need to get value from the database , so using a texbox so that client type anything and i can search from database.
My code is
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = " + textBox_cardNumber.Text;
the above is not my full code but here in my code i am using textbox_cardNumber ...
I want that in quotes ''
it should be like
Select distinct transactionName from dbo.tbl where terminalId = '0097'
So my question is how to get in quotes???
Use a parameterized query like this
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl " +
"where terminalId = #id";
sqlCmd.Parameters.AddWithValue("#id", textBox_cardNumber.Text);
....
In this way you defer the job to recognize your data (the textbox text) as a string to the Framework code that knows how to correctly quote your value. Also you remove the possibilities of Sql Injection attacks
"'" + textBox_cardNumber.Text + "'";
I hope I understood you!
You can also try this, but this is not good practice, used always Parameter.
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '" + textBox_cardNumber.Text +"'";
You can try this code:
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '"
+ textBox_cardNumber.Text+"'";
Instead of string concatenation, you can should use parameterized sql instead. Because this kind of codes are open for SQL Injection attacks.
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "SELECT DISTINCT transactionName FROM dbo.tbl
WHERE terminalId = #terminalID";
sqlcmd.Parameters.AddWithValue("#terminalID", textBox_cardNumber.Text);
A side note, take a look at SQL Injection Attacks by Example
You need to make use of prepared statements in which you use parameters.
Otherwise, you need to add quotes around your input string, but it will leave you open for SQL injection

Categories

Resources