'MySQL Connector SQL Query using LIKE

I have two sets of similar codes that gives different output. The first example does not return any output but the second example returns a output using the same search input.

First Example:

    sql = "SELECT accessionID, title, ISBN, publisher, publicationYear FROM Books WHERE %s LIKE %s";

    cursor.execute(sql,(col, "%" + values + "%",))

Second Example:

    sql = "SELECT accessionID, title, ISBN, publisher, publicationYear FROM Books WHERE title LIKE %s";

    cursor.execute(sql,("%" + values + "%",))

The codes that I am trying to code out is that WHERE is dynamic that depends on which text field user searches on. For example, if a user searches something on the title text box, it will only look into Title.

Another way I could think of is to use If conditions to hardcode, but it only works for the first If conditions and subsequent one does not work.

My question is how to make the SQL line dynamic (using first example) in the sense that I can do two %s in the SQL query line and still get the same output?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source