Search code examples
c#oledbsql-like

C# Oledb like statement not returning any results


I'm making a simple asp.net/c# application and everything with the Oledb worked just fine until now. The like statement is just not working through c#, it worked as a SQL Query in Access. I also tried just using '*a*' instead of '*@uname*' but it still didn't return anything.

OleDbDataAdapter dataAdapter = new OleDbDataAdapter(
    "SELECT accounts.ID, uname, firstname, lastname, description FROM accounts, profiles " +
    "WHERE accounts.ID = profiles.ID AND uname like '*@uname*'", connection);
dataAdapter.SelectCommand.Parameters.Add("@uname", OleDbType.VarChar).Value = tbxFilter.Text;

Solution

  • Well, from here I can see a fast way to fix it:

    WHERE accounts.ID = profiles.ID AND uname like @uname
    

    and then your parameter should be defined like this:

    dataAdapter.SelectCommand.Parameters.Add("@uname", OleDbType.VarChar).Value = "%" + tbxFilter.Text + "%" 
    

    or

    dataAdapter.SelectCommand.Parameters.Add("@uname", OleDbType.VarChar).Value = "*" + tbxFilter.Text + "*".
    

    A side note: if I were you, I would not include the tbxFilter.Text directly. Instead, you should use this:

    tbxFilter.Text.Replace("'", "''")
    

    since a ' sign in your parameter will hurt your SQL query if not doubled. Either that or you perform this safety check on your text control's handlers.