SQL Alchemy参数化查询,将绑定表名称作为参数给出错误

时间:2018-09-25 09:15:15

标签: python sql sql-parametrized-query

我在SQL炼金术中使用Text对象进行参数化查询,并且得到不同的结果。

工作示例:

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})

产生 sqlalchemy.exc.ProgrammingError 的示例:( pymysql.err.ProgrammingError )(1064,“您的SQL语法有错误)

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})

关于如何使用动态表名运行查询的任何想法,这些动态表名也可以防止sql注入?

2 个答案:

答案 0 :(得分:0)

我使用PostgreSQL和psycopg2后端。我能够使用:

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, )
)

答案 1 :(得分:-1)

我想为时已晚。 您可以利用用python编写的好处:

要使用的库:

import sqlalchemy
from sqlalchemy import create_engine, MetaData, Table, func, event
from sqlalchemy.sql import text
from urllib.parse import quote_plus

连接(在您的示例中没有看到-这里是sql azure的连接):

params = urllib.parse.quote_plus(r'...')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine_azure = create_engine(conn_str, echo=True)

您的示例:

db_table = 'Cars'
id_cars = 8
query = text('SELECT * FROM ' + db_table + 'WHERE idCars = ' + id_cars)
connection = engine.connect()
connection.execute(query)
connection.close()

我希望它会有所帮助。 BR