我编写了一个函数来查看数据库中的记录,如下所示:
我尝试将其插入树中并稍后显示,但是我无法执行此操作,弹出以下错误。
我无法理解这是为什么发生错误及其含义。
错误:
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\tp.py", line 532, in <module>
main()
File "C:\Users\Lenovo\Desktop\tp.py", line 522, in main
application = Detail (root)
File "C:\Users\Lenovo\Desktop\tp.py", line 89, in __init__
self.viewing_record()
File "C:\Users\Lenovo\Desktop\tp.py", line 115, in viewing_record
for row in db_row:
TypeError: 'int' object is not iterable
功能:
def viewing_record (self):
record = self.tree.get_children()
for element in record:
self.tree.delete(element)
query = 'SELECT * FROM Student ORDER BY Student_Name DESC'
db_row = self.run_query (query)
for row in db_row:
self.tree.insert ('', 0, text = (row[0]), values = (row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9]))
我希望它能够运行并将值插入树中,稍后将显示该树。
def run_query (self, query, parameters = ()):
db = MySQLdb.connect(host="127.1.1.0", # your host, usually localhost
user="**", # your username
passwd="***",
db="***") # name of the data base
cursor = db.cursor()
query_result = cursor.execute (query, parameters)
db.commit()
return query_result
答案 0 :(得分:1)
看来db_row
不是一个可迭代的对象。
在可运行代码方面没有更多可做之处,恐怕我们所能提供的最好的就是建议。
尝试插入良好的旧打印语句,例如:
print(db_row)
print(type(db_row))
db_row = self.run_query (query)
之后,看看那里发生了什么
答案 1 :(得分:1)
如果您使用的是Python DB API。然后run_query
可能会返回选择的行数。您需要从用于查询的游标中获取结果以获取行。这是来自PyMySQL文档的示例:
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
请注意,用于运行查询的cursor
对象和fetchone()
方法将获得一行。有一种类似的方法fetchall()
获取list
中的所有行。您将可以遍历该列表。
https://pymysql.readthedocs.io/en/latest/user/examples.html
答案 2 :(得分:0)
从错误消息中,看来db_row
是int
,而不是您所期望的。
尝试打印db_row
,然后查看返回的内容而不是您的预期值...