python-3.x - 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
解决方案
to 的第二个参数mycursor.execute
必须是包含要插入查询的值的可迭代对象
您可以使用 list:mycursor.execute(query, [id])
或单元素元组:mycursor.execute(query, (id,))
注意逗号。(id)
与 相同id
。在 python 中,逗号是创建元组,而不是括号。
推荐阅读
- powershell - 还原点信息 Veeam PowerShell
- crystal-reports-xi - 检查时间范围内的时间变量
- javascript - 使用 svg 渲染图像标签时,使用酶反应组件单元测试失败
- python - 应用在父文件夹中的文件夹上运行的脚本
- java - Jenkins Java 构建无法执行 Putty PSCP
- python - pip install presto:命令“python setup.py egg_info”失败,错误代码为1
- python - 如何在多窗口中绘画?
- unity3d - 如何调试不在 Unity 编辑器中运行的服务?(即 AdMob)
- terraform - terraform:对列表执行地图操作?
- c# - System.IO,文件保存在哪里?