Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Alchemy Parametrized Query , binding table name as parameter gives error

I am using parametrized query utilizing Text object in SQL alchemy and are getting different result.

Working example:

import sqlalchemy as sqlal
from sqlalchemy.sql import text

    db_table = 'Cars'
    id_cars = 8
    query = text("""SELECT * 
                    FROM Cars 
                    WHERE idCars = :p2
                 """)
    self.engine.execute(query, {'p2': id_cars})

Example that produces sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, "You have an error in your SQL syntax)

import sqlalchemy as sqlal
from sqlalchemy.sql import text

    db_table = 'Cars'
    id_cars = 8
    query = text("""SELECT * 
                    FROM :p1 
                    WHERE idCars = :p2
                 """)
    self.engine.execute(query, {'p1': db_table, 'p2': id_cars})

Any idea on how I can run the query with a dynamic table name that are also protected from sql injection?

like image 575
H. Tao Avatar asked Sep 25 '18 09:09

H. Tao


People also ask

Is SQLAlchemy slow?

SQLAlchemy is very, very fast. It's just that users tend to be unaware of just how much functionality is being delivered, and confuse an ORM result set with that of a raw database cursor. They are quite different, and SQLAlchemy offers many options for controlling the mixture of "raw" vs.

Is SQLAlchemy good?

SQLAlchemy is the ORM of choice for working with relational databases in python. The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started.

How do I write SQL query in SQLAlchemy?

We can write any conventional SQL query inside the text function enclosed by “”. Now, passing this SQL query to execute the function the engine object which we created while connecting the database will interpret this and convert this query to SQLAlchemy compatible format and results in the result.


1 Answers

I use PostgreSQL and psycopg2 backend. I was able to do it using:

from psycopg2 import sql
from sqlalchemy import engine

connection: sqlalchemy.engine.Connection
connection.connection.cursor().execute(
    sql.SQL('SELECT * FROM {} where idCars = %s').format(sql.Identifier(db_table)),
    (id_cars, )
)
like image 170
maciek Avatar answered Oct 11 '22 13:10

maciek