我正在尝试将如下列表传递给 sql 查询
x = ['1000000000164774783','1000000000253252111']
我正在使用 sqlalchemy 和 pyodbc 连接到 sql:
import pandas as pd
from pandas import Series,DataFrame
import pyodbc
import sqlalchemy
cnx=sqlalchemy.create_engine("mssql+pyodbc://Omnius:MainBrain1@172.31.163.135:1433/Basis?driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0")
我尝试在 sql 查询中使用各种字符串格式函数。下面是其中之一
xx = ', '.join(x)
sql = "select * from Pretty_Txns where Send_Customer in (%s)" % xx
df = pd.read_sql(sql,cnx)
他们似乎都把它转换成数字格式
(1000000000164774783, 1000000000253252111) instead of ('1000000000164774783','1000000000253252111')
因此查询失败,因为 Send_Customer 的数据类型在 SQL 中是 varchar(50)
ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][SQL Server Native Client 11.0]
[SQL Server]Error converting data type varchar to numeric. (8114) (SQLExecDirectW)')
[SQL: 'select * from Pretty_Txns where Send_Customer in (1000000000164774783, 1000000000253252111)']
最佳答案
正如对其他答案的评论中所述,该方法可能会因多种原因而失败。您真正想要做的是创建一个具有所需数量的参数占位符的 SQL 语句,然后使用 .read_sql_query()
的 params=
参数提供值:
x = ['1000000000164774783','1000000000253252111']
placeholders = ','.join('?' for i in range(len(x))) # '?,?'
sql = f"select * from Pretty_Txns where Send_Customer in ({placeholders})"
df = pd.read_sql_query(sql, cnx, params=x)
关于python - 将值列表从 Python 传递到 SQL 查询的 IN 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42123335/