我正在尝试将列表绑定到sqlalchemy中的原始SQL查询中的参数。 This post提出了使用psycopg2
进行此操作的好方法。
some_ids = [1, 2, 3, 4]
query = "SELECT * FROM my_table WHERE id = ANY(:ids);"
engine.execute(sqlalchemy.sql.text(query), ids=some_ids)
但是,对于SQL Server
pyodbc
的环境,这似乎不起作用。只添加了一个"?"
而不是4个。
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError)
('Invalid parameter type. param-index=0 param-type=tuple', 'HY105')
[SQL: 'SELECT * FROM my_table WHERE id = ANY(?);'] [parameters: ((1, 2, 3, 4),)]
有没有办法让这项工作?如果可能,我想避免manually creating placeholders。
sqlalchemy version = 1.0.13,pyodbc version = 4.0.16
答案 0 :(得分:0)
这似乎对我有用:
SELECT post_id,
'$order_company' AS Company,
MAX(IF(meta_key = 'additional_volunteers', meta_value, '')) AS Volunteers,
MAX(IF(meta_key = '_paid_date', meta_value, '')) AS Date,
...
FROM wp2_postmeta
WHERE post_id = (SELECT post_id FROM wp2_postmeta
WHERE meta_key = '_billing_company'
AND meta_value = '$order_company')
打印生成的SQL语句,然后打印查询结果
from sqlalchemy import create_engine
from sqlalchemy.sql import table, column, select, literal_column
engine = create_engine('mssql+pyodbc://SQLmyDb')
cnxn = engine.connect()
some_ids = [2, 3]
sql = select([literal_column('*')]).where(column('ID').in_(some_ids)).select_from(table('People'))
print(sql)
print('')
params = {":ID_" + str(x+1): some_ids[x] for x in range(len(some_ids))}
rows = cnxn.execute(sql, params).fetchall()
print(rows)