Like Operator Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • incinerator
    New Member
    • May 2010
    • 3

    Like Operator Problem

    I am writing code to search for books where some string is within the book's name

    it works fine when i set the search parameter to the whole name of the book but when i use the % sign wildcard no results seem to generate

    this is my code :

    Code:
    OleDbConnection myConn = null;
    string ConnString = @"Provider=Microsoft.Jet.OLEDB.4.0;User Id=;Password=;Data Source=Library.mdb";
    
    myConn = new OleDbConnection(ConnString);
    
    string OleDb = "SELECT Nom,Auteur,DateEdition  FROM Livres WHERE Nom Like '%bookname%'";
    
    OleDbCommand cmd = new OleDbCommand(OleDb,myConn );
    cmd.Parameters.Add("@bookname", txtfind.Text);
    
    dt = new DataTable();
    OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
    ad.Fill(dt);
    dgsearchbooks.DataSource = dt;
    i know it's something in the sql query i just cant seem to figure it out.
  • incinerator
    New Member
    • May 2010
    • 3

    #2
    SOLVED

    string OleDb = "SELECT Nom,Auteur,Date Edition FROM Livres WHERE Nom Like '%"+txtfind.Tex t+"%'";

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      If that wasn't the solution to it, maybe it could be this:
      In MS access you use the * as the wildcard and not the % like SQLServer

      Comment

      • incinerator
        New Member
        • May 2010
        • 3

        #4
        i am Indeed using an ms access database but using the % wildcard sign worked for me , but thanks for your reply, appreciated.

        Comment

        • Christian Binder
          Recognized Expert New Member
          • Jan 2008
          • 218

          #5
          I think, the problem was that you've escaped the parameter and missed the @-sign.

          Code:
          string OleDb = "SELECT Nom,Auteur,DateEdition FROM Livres WHERE Nom Like '%bookname%'";
          // ...
          cmd.Parameters.Add("@bookname", txtfind.Text);
          Right:


          Code:
          string OleDb = "SELECT Nom,Auteur,DateEdition FROM Livres WHERE Nom Like '%' + @bookname + '%'";
          // ...
          cmd.Parameters.Add("@bookname", txtfind.Text);
          OR (apply the percent-signs on parameter addition)

          Code:
          string OleDb = "SELECT Nom,Auteur,DateEdition FROM Livres WHERE Nom Like @bookname";
          // ...
          cmd.Parameters.Add("@bookname", "%" + txtfind.Text + "%");

          Comment

          • Curtis Rutland
            Recognized Expert Specialist
            • Apr 2008
            • 3264

            #6
            The last thing you want to do is remove the parameter altogether from your query. That leaves you vulnerable to SQL injection attacks. Always use parameterized queries.

            Comment

            Working...