我试图在我的表中插入整数值,但我遇到了“值错误”
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)
最佳答案
来自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/