如何解决数据库行 len() 可以打印,但是这个值不能在 tkinter entry 中显示
我无法理解,为什么我可以打印行的值,但不能将其填充到 tkinter 条目中。
我的代码:
cursor.execute(‘SELECT * FROM contacts;’)
print(‘row in table contacts:’,len(cursor.fetchall())) # prints 104
self.no_count.set(len(cursor.fetchall())) # populate 0
有什么提示吗?
解决方法
您应该将获取的数据存储在一个变量中,然后通过该变量访问它。这是因为游标就像一个 Python 生成器,一旦使用 cursor.fetchall()
,结果将不再包含结果。因此,请执行以下操作:
cursor.execute('SELECT * FROM contacts;')
data = cursor.fetchall() # Store in variable
print(f'row in table contacts: {len(data)}') # Used f strings instead of comma(can be ignored)
self.no_count.set(len(data))
或者您也可以采用每次重复查询的低效方式,例如:
cursor.execute(‘SELECT * FROM contacts;’)
print(f‘row in table contacts: {len(cursor.fetchall())}')
cursor.execute(‘SELECT * FROM contacts;’) # Repeat the query
self.no_count.set(len(cursor.fetchall())) # Fetch again
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。