如何使用 pyodbc 在 python 中使用列表作为 SQL 连接的参数
how to use a list as a parameter for SQL connection in python using pyodbc
我正在学习 python,我正在尝试将参数作为 WHERE 子句的一部分进行传递。我正在使用 pandas 和 pyodbc。到目前为止,这是我尝试过的。我首先从 pandas 数据框中获取 c 列的数据,并将其转换为名为 df_col 的列表,其中包含大约 100 个数值
df_col=df['data_for_colc'].tolist()
然后,我执行 SQL 语句:
execu = mycursor.execute(
"""
Select
columnA
,columnb
,columnc
where
columnc in (?)
""",df_col)
rows = mycursor.fetchall()
print(rows)
我可以从 SQL 服务器连接和下载数据,但我无法传递参数。我只需要能够根据我使用 100 个值创建的列表下载这 100 行,但我收到错误消息:('42000', "[42000] [Microsoft][ODBC SQL 服务器驱动程序][ SQL服务器]','附近的语法不正确。(102) (SQLExecDirectW)")
如有任何帮助,我们将不胜感激。谢谢
你必须生成所有这些问号...
execu = mycursor.execute(
"""
Select
columnA
,columnb
,columnc
where
columnc in ({})
""".format(','.join("?"*len(df_col))), df_col)
rows = mycursor.fetchall()
print(rows)
语法错误是因为您在查询中遗漏了 FROM
子句。
修复该问题后,IN()
列表中的 ?
需要与 df_col
.
中的元素一样多
placeholders = ", ".join(["?"] * len(df_col))
sql = """
SELECT columnA, columnB, columnC
FROM yourTable
WHERE columnc IN (""" + placeholders + ")"
execu = mycursor.execute(sql, df_col)
rows = mycursor.fetchall()
print(rows)
我正在学习 python,我正在尝试将参数作为 WHERE 子句的一部分进行传递。我正在使用 pandas 和 pyodbc。到目前为止,这是我尝试过的。我首先从 pandas 数据框中获取 c 列的数据,并将其转换为名为 df_col 的列表,其中包含大约 100 个数值
df_col=df['data_for_colc'].tolist()
然后,我执行 SQL 语句:
execu = mycursor.execute(
"""
Select
columnA
,columnb
,columnc
where
columnc in (?)
""",df_col)
rows = mycursor.fetchall()
print(rows)
我可以从 SQL 服务器连接和下载数据,但我无法传递参数。我只需要能够根据我使用 100 个值创建的列表下载这 100 行,但我收到错误消息:('42000', "[42000] [Microsoft][ODBC SQL 服务器驱动程序][ SQL服务器]','附近的语法不正确。(102) (SQLExecDirectW)")
如有任何帮助,我们将不胜感激。谢谢
你必须生成所有这些问号...
execu = mycursor.execute(
"""
Select
columnA
,columnb
,columnc
where
columnc in ({})
""".format(','.join("?"*len(df_col))), df_col)
rows = mycursor.fetchall()
print(rows)
语法错误是因为您在查询中遗漏了 FROM
子句。
修复该问题后,IN()
列表中的 ?
需要与 df_col
.
placeholders = ", ".join(["?"] * len(df_col))
sql = """
SELECT columnA, columnB, columnC
FROM yourTable
WHERE columnc IN (""" + placeholders + ")"
execu = mycursor.execute(sql, df_col)
rows = mycursor.fetchall()
print(rows)