Jonathan Cox Jonathan Cox - 11 months ago 82
SQL Question

SQLAlchemy error when adding parameter to string SQL query

I'm trying to compose a string SQL query using SQLALchemy 1.1.2. I followed the explanation from the docs about using textual SQL but encountered a syntax error when I ran the following code:

from sqlalchemy.sql import text

# Create a database connection called "connection"...

q = text('USE :name')
connection.execute(q, name='DATABASE_NAME')

Here's the error message:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''DATABASE_NAME'' at line 1") [SQL: u'USE %s;'] [parameters:

Since I'm using the named colon format and passing the parameters as arguments to
I can't figure out why this problem is arising. I'm using a MySQL server, but if I read the docs correctly the
method should be DB-agnostic.

Thanks in advance for the help.

Answer Source

According to the documentation you need to use the bindparams like so:

q = text('USE :name')

or like this:

q = text('USE :name')
q = q.bindparams(bindparam("name", String))

connection.execute(q, {"name": "DATABASE_NAME"})

This worked for me with no issues. Edit: I was wrong, it didn't work.

The problem is the bind params is going to auto wrap your value with a single quote. So what's happening is you get the final compiles statement (which is invalid syntax):


If you were to create the query: "Select * from mytable where column_a=:name"; this will work. Because it's wrapping the value with single quotes.

I would suggest for your use statement to do:

q = "USE {}".format("DATABASE_NAME") 

Or something similar.