python - 将数据框值作为参数添加到 sql 查询
问题描述
我正在尝试遍历数据框并从单个列中获取值以用作我在 sql 查询中的参数。
for index,frame in df1.iterrows():
sql = "select * from issuers where column_1 = %s;"
cur.execute(sql, frame['column_1'])
row = cur.fetchone()
id = row[0]
print id
但我收到以下错误
“TypeError:并非所有参数都在字符串格式化期间转换”
我该如何解决这个问题?如果我需要添加多个参数,我该怎么做?
解决方案
而不是这个:
cur.execute(sql, frame['column_1'])
尝试这个:
cur.execute(sql, [frame['column_1']])
的第二个参数execute
是一个列表,其中包含要插入的所有值sql
。
为了插入多个值,请使用以下内容:
sql = "select * from issuers where column_1 = %s and column_2 = %s;"
cur.execute(sql, ["val1", "val2"])
有关更多信息,请参阅文档
编辑
INSERT INTO
这是SQL 中的示例。
sql = "INSERT INTO user (firstname, lastname) VALUES (%s, %s)"
cur.execute(sql, ["John", "Doe"])
推荐阅读
- spring-integration - Spring 集成 - 无法在 BeanFactory 中查找名称为“55774d05-e054-4b71-bc7e-ecc53d029e75:20”的 MessageChannel
- python - Python 代码作为脚本在 ipython 中运行,但在 jupyter-notebook 中抛出错误
- angular - 获取动态构建的反应形式的第一个值
- here-api - HERE 地图 - 卡车限制
- r - 如何在 R 中更广泛地旋转 NoSQL 数据
- python - 如何在客户端机器上执行 python 脚本?
- flutter - 如何在 Visual Studio 代码中从颤振项目创建自己的 sdk
- cytoscape.js - 在 Cytoscape 中的节点内键入文本
- apache-kafka - 有人在使用 Kafka 进行蓝绿部署时遇到过问题吗?
- python-3.x - VSCode 从哪里获得文档字符串签名?