python - 将值列表从 Python 传递到 SQL 查询的 IN 子句

标签 python sql-server sqlalchemy pyodbc

我正在尝试将如下列表传递给 sql 查询

x = ['1000000000164774783','1000000000253252111']

我正在使用 sqlalchemypyodbc 连接到 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/

相关文章:

python - 在 Windows 7 上升级权限后 Esky 卡住

sql - 检查一个或多个 id 是否在 json 字符串中

c# - 将嵌套 SQL 查询转换为 LINQ 查询

python - sqlalchemy在一对多关系中添加 child

python - 如何使用 SQLAlchemy ORM 指定 PostgreSQL DateStyle 属性

python - 原始 SQL 到 sqlalchemy 语法

python - 无法使用 selenium webdriver + firefox 下载 PDF

python - Django 科学记数法输入验证

python - 我正在使用 pypyodbc.connect - 有没有办法给它一个应用程序名称?

sql-server - 如果子查询返回太多数据,我应该担心吗?