【问题标题】:psycopg2 TypeError: not all arguments converted to string when passing multiple parameterspsycopg2 TypeError:传递多个参数时并非所有参数都转换为字符串
【发布时间】:2018-09-07 04:32:19
【问题描述】:

我正在尝试使用 psycopg2 将多个值传递给我的 INSERT 函数。根据documentation,您必须通过一个列表或元组,我正在这样做,但它仍然因以下错误而中断:

“文件“c:\action.py”,第 42 行,在 putTicket 中 cur.execute(SQL, ins) TypeError: 在字符串格式化期间并非所有参数都转换了"

代码:

data = response.json()                  # get JSON response

record = data[0]                    # header row
col = record.keys()                 # column names
a = []

def putTicket(conn):
    cur = conn.cursor()

    for record in data:                     # data rows
        a = []
        y = record.values()                 # values on this row in an array

        for col in y:
            a.append(col)

    ins = tuple(a)

    SQL = "INSERT INTO fd_tickets VALUES (%s)"
    cur.execute(SQL, ins)


print("Using psycopg2...")

myConnection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database, port=port)
putTicket(myConnection)
myConnection.close()   

【问题讨论】:

  • 你试过这个:cur.execute("insert into fd_tickets values %s", [ins]) 吗? (你真的应该在插入语句中说明列名。)
  • 这解决了它。我同意,但是如果我每次都插入整行有关系吗? DB 极不可能发生变化。

标签: python psycopg2


【解决方案1】:

您有多个值,但只有一个占位符。您需要与元组中的值一样多的占位符。

placeholders = ','.join(['%s'] * len(a))
SQL = "INSERT INTO fd_tickets VALUES ({})".format(placeholders)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多