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

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

Related

how to change sql statement to parameterized query?

I have an sql query that I need change to parameters so I can avoid sql injection.
adapter.SelectCommand.CommandText = #"SELECT c.*,(Select Initials FROM users WHERE User_ID = c.CreatedByUser) AS CreatedBy, (SELECT Initials FROM users WHERE User_ID = c.ModifiedByUser) AS ModifiedBy FROM currency c WHERE c.Company_ID = " + Company_ID + " AND c.CurrencyCode = '" + Code.Replace("'", "''") + "' ORDER BY c.Description
adapter.SelectCommand.Parameters.Add(new MySqlParameter("company_ID", Company_ID));
adapter.SelectCommand.Parameters.Add(new MySqlParameter("code", Code));
I know for Company_ID I need to change it to WHERE c.Company_ID = ?company_ID but I am not sure what to do for c.CurrencyCode = '" + Code.Replace("'", "''") + "'
I just don't know how to change the Code.Replace part, since its not a simple as company_ID
As per here
Try using (for odbc for example):
cmd.Parameters.Add("?CURRENCY", OdbcType.VarChar, Code.Replace("'", "''"))
Odbc approach
OdbcCommand cmd = sql.CreateCommand();
cmd.CommandText = "SELECT UNIQUE_ID FROM userdetails WHERE USER_ID IN (?, ?)";
cmd.Parameters.Add("?ID1", OdbcType.VarChar, 250).Value = email1;
cmd.Parameters.Add("?ID2", OdbcType.VarChar, 250).Value = email2;
For oracle:
//create SQL and insert parameters
OracleCommand cmd = new OracleCommand("insert into daily_cdr_logs (message) values (:_message)", con);
cmd.Parameters.Add(new OracleParameter("_message", msg));
For mysql:
cmd = new MySqlCommand("SELECT * FROM admin WHERE admin_username=#val1 AND admin_password=PASSWORD(#val2)", MySqlConn.conn);
cmd.Parameters.AddWithValue("#val1", tboxUserName.Text);
cmd.Parameters.AddWithValue("#val2", tboxPassword.Text);
cmd.Prepare();
So a parameterized query (to me at least) generally means that you have created a stored procedure on your database and then use your code to execute the stored procedure while passing in the relevant parameters.
This has a couple of benefits
DRY - you don't have to repeat the query in code, you can just call the execute method and pass in the appropriate parameters
Helps prevent SQL injection - You can only modify the parameters which hopefully will be sanitized before being passed to the query
Here is how to create a stored procedure according to MSDN
and
Here is how to execute a a stored procedure according to MSDN
If you are determined to do it via LINQ, MSDN has what you are looking for here
EDIT: It seems you are concerned about sql-injection (which is good!), here is an article (again from MSDN) that covers that topic pretty extensively
I have the answer. c.CurrencyCode = '" + Code.Replace("'", "''") + "' simply changes to c.CurrencyCode = ?code

How to use like operator with %?

I am creating a search bar and I am having a hard time constructing the correct query for that. Here is my code:
SqlCommand command1 = new SqlCommand(
"Select * from tbl_customer where customer_name like '%''"+ textBox1.Text +"''%' ",
MySqlConnection);
SqlCommand command1 = new SqlCommand("Select * from tbl_customer where customer_name like #search_value", MySqlConnection);
command1.Parameters.AddWithValue("#search_value","%" + textBox1.Text + "%");
You are adding too many 's.
SqlCommand command1 = new SqlCommand(
"Select * from tbl_customer where customer_name like '%"+ textBox1.Text +"%' ",
MySqlConnection);
Note that I have removed the extra 's after the first % and before the last %.
However, you should be careful about SQL injection and use parameters instead of directly adding control values into your query.
SqlCommand command1 = new SqlCommand(
"Select * from table-name where column-name like '%"+ textboxid.Text +"%' ",
MySqlConnection);
If u making a sample program then ok it will work ,but if you are looking for a professional use software or website then don't go with this method . Check sql injection because here you are directly adding the control values in query

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 + "'";
^

Concatenation in C# with SQL Query for Access Database

I have an Access Db with C# and I am doing a concatenation in sql query aftere where clause but I am getting the following error
"Syntax error (missing operator) in query expression"
My code is below
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL=" + GlobalData.Email;
Please tell me what is causing the error and what the correct syntax is for concatenation.
You'd better use SqlParameter (more secure):
SqlCommand cmd = new SqlCommand("SELECT * FROM Temp1 WHERE Email LIKE #email")
cmd.Parameters.Add(new SqlParameter("email", GlobalData.Email));
To answer to the original question:
Using direct concatenation, without string delimiter, your query become:
SELECT * FROM Temp1 WHERE Email LIKE email#email.com
instead of
SELECT * FROM Temp1 WHERE Email LIKE 'email#email.com'
I think your your problem is missing quotes. Try this:
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL='" + GlobalData.Email + "'";
But that method can lead to SQL injection if you don't validate the email. Although there is nothing wrong with the above code, if data is validated, I do prefer to use SQL Parameters:
SqlCommand cmd = new SqlCommand( "SELECT * FROM Temp1 WHERE Email = #Email" )
cmd.Parameters.Add( new SqlParameter( "Email" , GlobalData.Email ) );
Try using Parameterised queries instead. It's usually the norm when working with SQL queries, for security reasons as well as readability.
You don't have any apostrophes around the string literal, so your query will end up like:
Select * from TEMP1 WHERE EMAIL=someone#somesite.com
This will of course cause a syntax error. You need the apostrophes around the string:
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL='" + Replace(GlobalData.Email, "'", "''") + "'";
However, encoding strings correctly is not trivial. (The above method works for Access and Microsoft SQL Server, but other databases needs other methods.) You should rather use parametrised queries:
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL=#email";
Then you add a parameter to the command object, for example:
cmp.Parameters.Add("#email", DbType.VarChar, 300).Value = GlobalData.Email;
Try something like below
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL='" + GlobalData.Email + "'";
i'm not sure about the error, but you should try it like that
cmd.CommandText = string.Format("SELECT * FROM TEMP1 WHERE EMAIL='{0}'", GlobalData.Email);
That way you don't need to mess with ugly concatination that btw, takes alot of memory usage.

Prevent SQL Injection in SELECT statement

I am using VS2005 C# ASP.NET and SQL Server 2005.
I have a search function on my asp page and I feel that my SELECT query is vulnerable to SQL injection.
This is my current SELECT statement:
string LoggedInUser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [empUser] LIKE '%"+LoggedInUser+"%'";
SqlDataSource1.DataBind();
*where searchTB is my search text box; DropDownList1 is my search category; and LoggedInUser is the username of the logged in user.
I have implemented parameter instead of concatenation in one of my INSERT statement:
string sql = string.Format("INSERT INTO [TABLE2] (Username) VALUES (#Username)");
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("Username", usernameTB.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
I would like to change my SELECT statement like my INSERT statement, using parameter instead. May I know how should I change it?
Thank you
You can add parameters to your selectcommand using
SqlDataSource s = new SqlDataSource();
s.SelectParameters.Add("paramName", "paramValue");
There are other parameter collections for delete, update and insert too.
s.DeleteParameters
s.UpdateParameters
s.InsertParameters
More Information:
MSDN: SqlDataSource.SelectParameters Property
Programmatically Using SqlDataSource
hope this helps
See Using Parameters with the SqlDataSource Control
And SqlDataSource.SelectParameters Property
You can specify SelectParameters Property for SqlDataSource to use parameterized SQL query
Write a method that gets the data sourse and use sql parameters for the query. Here is a good example how to add parameters in a command object
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
I would use a method for the query so that I separate the Database Access from the UI functionality. Also, this allows to reuse the query.
It's not a straightforward task to dynamically specify a fieldname in query, so I'd suggest just doing switch/case validation for field name, like this:
switch (DropDownList1.Text)
{
case "ValidField1":
case "ValidField2":
...
break;
default:
throw new ArgumentException(...); // or prevent query execution with some other statement
}
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like #value AND [empUser] LIKE #user";
SqlDataSource1.SelectParameters.Add("value", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("user", "%"+LoggedInUser+"%");
SqlDataSource1.DataBind();
You can simply use a filter expression for the SQL datasource SQL Datasource filter expression
You can write your own select function method with object datasource/datatable

Categories

Resources