我正在学习python,我试图将参数作为WHERE子句的一部分传递。我正在使用熊猫和pyodbc。这是我到目前为止所尝试的内容。我首先从pandas数据帧中获取列c的数据,并将其转换为名为df_col的列表,该列表具有大约100个数值
import sys
from functools import wraps
def withCallerContext(fn):
@wraps(fn)
def wrapped(*a, **k):
frame = sys._getframe(0)
while 'cx' not in frame.f_globals:
frame = frame.f_back
if frame is None:
raise ValueError("must set cx in calling context")
cx = frame.f_globals['cx']
return fn(*a, cx = cx, **k)
return wrapped
@withCallerContext
def function1(s1: str, cx: Context = None):
print(f'{cx.s} {s1}!')
然后,我执行SQL语句:
df_col=df['data_for_colc'].tolist()
我能够连接并从SQL服务器下载数据,但我无法传递参数。我只需要能够根据我使用100个值创建的列表下载这100行,但是我收到错误:(' 42000'," [42000] [Microsoft] [ODBC SQL服务器驱动程序] [SQL Server]','附近的语法不正确。(102)(SQLExecDirectW)")
任何帮助将不胜感激。感谢
答案 0 :(得分:1)
语法错误是因为您在查询中遗漏了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)
。
vm.imageR = $resource("", {}, {
getFile: {
url: '/api/imager/:fileId',
method: 'GET',
transformResponse: function(data, headersGetter) { return { data : data }},
isArray: false,
params: {
fileId: '@fileId'
}
},
...
答案 1 :(得分:0)
你必须生成所有这些问号...
execu = mycursor.execute(
"""
Select
columnA
,columnb
,columnc
where
columnc in ({})
""".format(','.join("?"*len(df_col))), df_col)
rows = mycursor.fetchall()
print(rows)