python-3.x - 值错误 :unsupported format character 'd' (0x64) at index %Id

标签 python-3.x postgresql psycopg2

我试图在我的表中插入整数值,但我遇到了“值错误”

import psycopg2

def connect():
    con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
    cur=con.cursor()
    cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL)")
    con.commit()
    con.close()

def insert(title,author,year,isbn):
    con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432'")
    cur=con.cursor()
    cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%d,%d)",(title,author,year,isbn))
    con.commit()
    con.close()


connect()
insert("the sun","helen",1997,23456777)

enter image description here

最佳答案

来自Psycopg FAQ :

Q: I can’t pass an integer or a float parameter to my query: it says a number is required, but it is a number!

A: In your query string, you always have to use %s placeholders, even when passing a number. All Python objects are converted by Psycopg in their SQL representation, so they get passed to the query as strings. See Passing parameters to SQL queries.

所以我猜你只需要将 %d 替换为 %s

关于python-3.x - 值错误 :unsupported format character 'd' (0x64) at index %Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47695194/

相关文章:

algorithm - 打印(或输出到文件)欧几里得算法的步骤数表

python - 使用 jaydebeapi3 连接到 Apache Phoenix

python - 为什么在这个函数中使用self?

sql - 在postgresql中的两个用户之间的对话中获取最新消息

sql - 如何在 SQL 中找到所有行的每组最大值?

python - psycopg2,我应该分块提交吗?

python - 错误的子类,计算它被引发的次数

postgresql - RDBMS 是否如 Hadoop : The definitive guide? 中所述那样糟糕

django - Heroku 未从 requirements.txt 安装 psycopg2

python-3.x - 无法在 ubuntu 18.04 上安装 psycopg2