简体   繁体   中英

How to use the wildcard% in mysqlcommand using 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 + "%");
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM