Reputation: 89
I tried to insert integer values in my table, But i was subjected to "Value Error"
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)
Upvotes: 3
Views: 7907
Reputation: 85
From psycopg documentation we can find this explanation:
The variables placeholder must always be a
%s
, even if a different placeholder (such as a%d
for integers or%f
for floats) may look more appropriate for the type. You may find other placeholders used in Psycopg queries (%b
and%t
) but they are not related to the type of the argument...
Source: documentation on Passing parameters to SQL queries
Upvotes: 0
Reputation: 2387
From the 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.
So I guess you just have to replace the %d
with %s
.
Upvotes: 14