Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to run a SQL query in my Flask application to search a database. However, I get an error when I run the query:

db.execute("SELECT * FROM books WHERE author LIKE '%:author%' ", {"author":query})

The resulting error is this (passed 'Tom' in my input):

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "Tom" LINE 1: SELECT * FROM books WHERE author LIKE '%'Tom'%' [SQL: SELECT * FROM books WHERE author LIKE '%%%(author)s%%' ] [parameters: {'author': 'Tom'}] (Background on this error at: http://sqlalche.me/e/f405)

I've tested the query with a hard coded value and it works fine. I would like to know what is causing the error and how to fix it.

You need string concatenation. Many SQL databases support concat() (and other have an equivalent function or operator, such as standard operator || ):

db.execute("SELECT * FROM books WHERE author LIKE CONCAT('%', :author, '%')", {"author":query})

Another option is to concatenate '%'s around your parameter in your application first, and then pass it to the query.