0

Hi..i tried to search for an entry in my table that holds both text and integer values..my code works well on sqlite3 database...but throws Data Error on Postgresql database..

import psycopg2
class database:

    def __init__(self):

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

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          #print("already exists..")
          pass

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title="",author="",year="",isbn=""):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.ferchall()
        print(row)

db=database()
#db.insert("The Naughty","AparnaKumar",1995,234567654)
db.view()
db.search(year=1995)

psycopg2.Data Error: invalid input syntax for integer:" "

2
  • Pass the isbn as null not as empty string Commented Dec 7, 2017 at 17:39
  • ISBNs are either 10 or 13 characters in length, which the 10-digit version having the potential to start with a zero. Not sure using integer for the data type in your table is a good idea. Commented Dec 7, 2017 at 17:51

1 Answer 1

1

This is what you want:

def search(self, title=None, author=None, year=None, isbn=None):
    self.cursor.execute("""
        select * 
        from books 
        where 
            (title = %(title)s or %(title)s is null)
            and
            (author = %(author)s or %(author)s is null)
            and
            (year = %(year)s or %(year)s is null)
            and
            (isbn = %(isbn)s or %(isbn)s is null)
        """,
        {'title': title, 'author': author, 'year': year, 'isbn': isbn}
    )
Sign up to request clarification or add additional context in comments.

1 Comment

That would likely solve the issue, but maybe explain why? Otherwise this is a code-only answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.