Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x psycopg2.数据错误:整数“的输入语法无效&引用;_Python 3.x_Postgresql_Psycopg2 - Fatal编程技术网

Python 3.x psycopg2.数据错误:整数“的输入语法无效&引用;

Python 3.x psycopg2.数据错误:整数“的输入语法无效&引用;,python-3.x,postgresql,psycopg2,Python 3.x,Postgresql,Psycopg2,您好..我试图在表中搜索一个同时包含文本和整数值的条目..我的代码在sqlite3数据库上运行良好…但在Postgresql数据库上抛出数据错误 import psycopg2 class database: def __init__(self): self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")

您好..我试图在表中搜索一个同时包含文本和整数值的条目..我的代码在sqlite3数据库上运行良好…但在Postgresql数据库上抛出数据错误

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)
这就是你想要的:

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

将isbn作为null而不是空字符串传递isbn的长度为10或13个字符,10位版本可能以零开头。不确定对表中的数据类型使用
integer
是否是一个好主意。这可能会解决问题,但可能会解释为什么?否则,这是一个代码唯一的答案。