12

我正在使用 SQL alchemy 中的 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, "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})

关于如何使用动态表名运行查询的任何想法,这些表名也受到 sql 注入的保护?

4

2 回答 2

5

我使用 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, )
)
于 2019-05-20T11:29:18.043 回答
-2

您可以使用 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()
于 2019-04-29T02:08:17.077 回答