【问题标题】:Problem with postgres passing parameters in pythonpostgres在python中传递参数的问题
【发布时间】:2019-09-27 19:11:27
【问题描述】:

我有这个代码,它取标题、isbn 或一本书的作者,并从数据库中检索所有匹配的数据。

问题在于传递参数行,它只检索第一条记录,关于用户输入的数据。

我尝试在数据库控制台中使用 select 语句 它并检索正确的语句,我知道 传递参数行的 cur.execute 是不正确的。 你能帮我解决这个问题吗?提前谢谢。

这是代码

class Searchb:
    def __init__(self,isbn,author,title):
        self.isbn=isbn
        self.author=author
        self.title=title

    def booksearch(self):
        query= "select author,title from books where isbn LIKE '%%s%%' OR author LIKE '%%s%%' OR title like '%%s%%' "
        cur.execute(query,(self.isbn,self.author,self.title),)
        book=cur.fetchmany()

【问题讨论】:

    标签: python postgresql


    【解决方案1】:

    您正在使用没有任何参数的 cur.fetchmany()。来自the docs

    每次调用获取的行数由参数指定。如果没有给出,游标的数组大小决定了要获取的行数。

    arraysize 默认为 1,这就是为什么你只得到 1 行。要么指定更高的迭代,直到你没有更多的结果,要么只使用cur.fetchall()

    【讨论】:

    • 不,我尝试使用 fetchall() 得到相同的结果。结果不正确。
    • 你说它只检索了第一条记录。结果有什么不正确的地方?
    • 检索数据库中的第一条记录或检索所有记录,无论您要求的是什么 isbn 或作者姓名或书名??
    【解决方案2】:

    问题出在 select 语句中,在将参数传递给数据库的同时,我可以找到带有 Like 的 select 语句的正确语法; postgres

    query="select author,title from books where isbn LIKE %s or author like %s or title like %s "
                  book_to_search=(self.isbn,self.author,self.title)
                  cur.execute(query,book_to_search)
                  book=cur.fetchall() 
    

    感谢大家!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2014-09-20
      相关资源
      最近更新 更多