How to use the wildcard% in mysqlcommand using c# - c#

Please help me guys, my professor has done this before but I forgot how. And if possible I need it right now. How do I use the wildcard % in this code? Thanks in advance!!
MySqlCommand SelectCommand = new MySqlCommand("select * from sms.members where memberFName +' '+ memberLName like'" +cmbmemsched.Text+ "';", myconn);

You'd better use parameterized queries to avoid SQL injection:
MySqlCommand selectCommand = new MySqlCommand(
"SELECT * FROM sms.members WHERE memberFName LIKE #memberFName;",
myconn
);
selectCommand.Parameters.AddWithValue(#memberFName, "%" + cmbmemsched.Text + "%");
In this example, the LIKE statement will look for the search phrase anywhere in the middle of the value. If you want to look for records that start with or end with the specified filter you will need to adapt the % in the parameter.
I'd also more than strongly recommend you wrapping your IDisposable resources such as SQL commands in using statement to ensure that they are properly disposed even if some exceptions are thrown:
using (MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM sms.members WHERE memberFName LIKE #memberFName;", myconn))
{
selectCommand.Parameters.AddWithValue(#memberFName, "%" + cmbmemsched.Text + "%");
}

Related

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

Syntax error in UPDATE statement OleDb Exception

I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here
I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"
Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.

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

SqlException: Incorrect syntax near the keyword 'AND'

I'm making a management program with C# & SQL Server 2008. I want to search records using Blood Group, District & Club Name wise all at a time. This is what is making prob:
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Table2
WHERE #Blood_Group =" + tsblood.Text + "AND #District =" + tsdist.Text +
"AND Club_Name =" + tscname.Text, Mycon1);
Can anyone tell me what is the correct syntax? Tnx in advance. :)
The correct syntax is to use parametrized queries and absolutely never use string concatenations when building a SQL query:
string query = "SELECT * FROM Table2 WHERE BloodGroup = #BloodGroup AND District = #District AND Club_Name = #ClubName";
using (SqlDataAdapter sda = new SqlDataAdapter(query, Mycon1))
{
sda.SelectCommand.Parameters.AddWithValue("#BloodGroup", tsblood.Text);
sda.SelectCommand.Parameters.AddWithValue("#District", tsdist.Text);
sda.SelectCommand.Parameters.AddWithValue("#ClubName", tscname.Text);
...
}
This way your parameters will be properly encoded and your code not vulnerable to SQL injection attacks. Checkout bobby tables.
Also notice how I have wrapped IDisposable resources such as a SqlDataAdapter into a using statement to ensure that it is properly disposed even in case of an exception and that your program will not be leaking unmanaged handles.
You forgot an AND (and possible an # in front of Club_Name?):
String CRLF = "\r\n";
String sql = String.Format(
"SELECT * FROM Table2" + CRLF+
"WHERE #Blood_Group = {0}" + CRLF+
"AND #District = {1} " + CRLF+
"AND Club_Name = {2}",
SqlUtils.QuotedStr(tsblood.Text),
SqlUtils.QuotedStr(tsdist.Text),
SqlUtils.QuotedStr(tscname.Text));
SqlDataAdapter sda = new SqlDataAdapter(sql, Mycon1);

Help me Fix this SQL Statement?

Can someone let me know what is wrong with my SQL Statement and how I can improve it?
da = new SqlDataAdapter("SELECT * FROM Guests"+" WHERE Students.name='" +
byNametextBox.Text + "'", MyConn);
An EXISTS predicate is slightly more efficient than a JOIN if you want only columns from one of the tables. Additionaly - never inject strings into SQL statements like that - you're just begging for SQL Injection attacks, or related crashes errors (Yes, I know it's a Forms application, but the same holds true. If you're searching for a name like "O'Leary", you'll get a crash).
SqlCommand cmd = new SqlCommand("SELECT * FROM Guests WHERE EXISTS (SELECT Id FROM Students WHERE Guests.StudentId = Students.Id And Students.name= #name)", MyConn);
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = byNametextBox.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
Note: Some people may argue that "SELECT *" is bad, and that you should consider specifying individual column names
You need to worry about SQL Injection. Put simply, SQL Injection is when a user is able to put arbitrary SQL statements into your query. To get around this, either use a Stored Procedure or a Parametrized SQL Query. An Example of a Parametrized SQL query is below:
SqlConnection conn = null;
SqlDataReader reader = null;
//Connection string goes here
string studentName = byNametextBox.Text;
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Guests "+" WHERE Students.name = #name", conn);
SqlParameter param = new SqlParameter("#name", SqlDbType.NVarChar, 50);
param.Value = studentName;
cmd.Parameters.Add(param);
reader = cmd.ExecuteReader();
//Do stuff with reader here
SqlDataAdapter("SELECT Guests.* FROM Guests,Students WHERE Guest.StudentId = Student.Id and Students.name='" + byNametextBox.Text + "'", MyConn);`
You need an Inner Join. I think it would be something like this:
SELECT Guests.* FROM Guests INNER JOIN Students ON Students.name = Guests.name WHERE Students.name = '" + byNametextBox.Text + "'"
Try it:
"SELECT g.*
FROM Guests g
INNER JOIN Students s ON g.StudentId = s.StudentId
WHERE Students.Name = '" + byNametextBox.Text + '"'
Assuming that the field wich relates both tables is StudentId.
Beware that SQL is not the same between different Servers. This statement will work on Sql Server, I don't know in others. Also, beware that you aren't protecting yourself on SQL Injection attacks. You should perform your query with parameters, instead of concatenating strings in the way you are doing it.
This is a simple query that you should know by yourself. You can search for tutorials on Google, but here is a generic introduction.

Categories

Resources