我使用列表传递到 Python 中 SQL 语句的 where 子句。当我执行代码时,我收到以下错误消息:此错误的背景:https://sqlalche.me/e/14/dbapi。它还在 Python 控制台中重复我的列表。
我到处搜索并多次更改代码,但收到相同的错误消息。
示例代码:
conx = sqlalchemy.create_engine("mssql+pyodbc://UID:PW@SERVERNAME/DB?driver=ODBC+Driver+17+for+SQL+Server",echo=False)
customer_exclude_query_sql = """
select distinct customer
from customer_table
where
customer NOT IN ({})
""".format(','.join(('?')*len(customer_exclude_list)))
df = pd.read_sql(sql=customer_exclude_query_sql,con=conx,params=customer_exclude_list)
这是 sqlalchemy 1.4 的。*
使用 sqlalchemy 的文本包装函数然后将参数绑定到那里可能更容易。 sqlalchemy.sql.表达式.文本
from sqlalchemy.sql import text
customer_exclude_query_sql = text("""
select distinct customer
from customer_table
where
customer NOT IN :customer_exclude_list
""").bindparams(customer_exclude_list=customer_exclude_list)
df = pd.read_sql(sql=customer_exclude_query_sql,con=conx)