2017-12-07 18 views
0

Hi..iは、テキストと整数values..myコードの両方を保持している私のテーブル内のエントリを検索してみましたがうまく機能しますsqlite3のデータベースに...しかし、これはあなたが望むものであるpsycopg2.Dataエラー:整数のための無効な入力構文:」 "

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:" "

+0

空の文字列ではなく、isbnをnullとして渡します。 –

+0

ISBNは、10桁の長さで、10桁の数字は0から始まる可能性があります。あなたのテーブルのデータ型に 'integer'を使うのは良い考えです。 – Nicarus

答えて

1

.. PostgreSQLデータベースにデータエラーがスローされます。

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} 
    ) 
+0

これはおそらく問題を解決するでしょうが、なぜその理由を説明できますか?それ以外の場合は、これはコードのみの回答です。 – Nicarus

+0

助けてくれてありがとう...それは動作します。 – kiruthika

関連する問題