Sqlalchemy mysql parameterized query
<p>I am trying to pass table name as variable into a sql query and execute it with a sqlalchemy cursor:</p>

<pre><code>from sqlalchemy.sql import text

cur = DB_ENGINE.connect()
p = cur.execute(text('select * from :table'), {'table':'person'}).fetchall()
print p
</code></pre>

<p>and I got this error message:</p>

<pre><code>ProgrammingError: (_mysql_exceptions.ProgrammingError) (1064, "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 ''person'' at line 1") [SQL: u'select * from %s'] [parameters: ('person',)]
</code></pre>

<p>where did I do wrong?</p>

<p>Placeholders can only represent VALUES. You cannot use them for sql keywords/identifiers.</p>

<p>If you need to dynamically change an identifier, then you'll have to build the query string yourself, e.g.</p>

<pre><code>sql = "SELECT foo FROM " + var_with_table_name + "WHERE somefield = ?"
</code></pre>

<p>which then leaves you open to SQL injection attacks to boot.</p>

python mysql sqlalchemy