首页 > 解决方案 > 将数据框值作为参数添加到 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:并非所有参数都在字符串格式化期间转换”

我该如何解决这个问题?如果我需要添加多个参数,我该怎么做?

标签: pythonpostgresqlpandas

解决方案


而不是这个:

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"])

推荐阅读