首页 > 解决方案 > TypeError:在与 postgresql 连接的 python 中的字符串格式化期间,并非所有参数都转换了

问题描述

代码中似乎没有错误,但不知道为什么我会得到这个。我正在创建一个简单的 GUI 应用程序,它将用户详细信息存储到数据库(postgresql)中,并且他们将能够搜索数据库中的条目。这个特定的错误发生在这个 search() 函数中,所以我没有添加其余的代码。如有必要,我可以添加它们。希望我能从这个社区得到一些解决方案。

def search(id):
    conn = psycopg2.connect(dbname="postgres",user="postgres",password="1018",host="localhost",port="5432")
    mycursor = conn.cursor()
    query = '''select * from demotab where id=%s '''
    mycursor.execute(query, (id))
    row = mycursor.fetchone()
    print(row)
    conn.commit()
    conn.close()

在下面收到此错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "c:\programdata\anaconda3\lib\tkinter\__init__.py", line 1702, in __call__
    return self.func(*args)
  File "appwithDB.py", line 51, in <lambda>
    search_button = Button(newframe, text="Search", command=lambda : search(entry_search.get()))
  File "appwithDB.py", line 71, in search
    mycursor.execute(query, (id))
TypeError: not all arguments converted during string formatting

标签: python-3.xdatabasestring-formattingpostgresql-9.5

解决方案


to 的第二个参数mycursor.execute必须是包含要插入查询的值的可迭代对象

您可以使用 list:mycursor.execute(query, [id]) 或单元素元组:mycursor.execute(query, (id,))

注意逗号。(id)与 相同id。在 python 中,逗号是创建元组,而不是括号。


推荐阅读