Search code examples
pythonsqlsqlitesql-like

search for data LIKE a variable but i want to find data like %?% but of course this doesn't work


Im trying to search for data LIKE a variable but i want to find data like %?% but of course this doesn't work i can use LIKE ? but i need to also find all values with e.g D and comes up with Dog

       search=self.text
    with sqlite3.connect('Data.db') as db:
        user_find = db.cursor()
        user_find.execute(
            'select * from "Animal Data" where Animal_ID LIKE ? or Animal_Name LIKE ? or Animal_Type LIKE ? or Animal_Gender LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE? or Animal_colour LIKE ? or Address LIKE ?'
            ,(search,search,search,search,search,search,search,search,search,))
        data = user_find.fetchall()
        print(data)

Solution

  • You should be binding to the ? placeholder the entire expression you want to appear in the LIKE statement. That is, if you wanted to search for any field having the letter D, you would bind the string %D% to your statement.

    search = '%' + search + '%'
    user_find = db.cursor()
    user_find.execute(
        'select * from "Animal Data" where Animal_ID LIKE ? or Animal_Name LIKE ? or Animal_Type LIKE ? or Animal_Gender LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE? or Animal_colour LIKE ? or Address LIKE ?',
        (search,search,search,search,search,search,search,search,search,)
    )
    data = user_find.fetchall()
    print(data)