我正在研究我的第一个(更大的)python应用程序,但我遇到了一些问题。我正在尝试使用web.py导入从表中选择条目(我使用这个,因为我将使用web前端)。
下面是我的(简化)代码:
db = web.database(dbn='mysql', host='xxx', port=3306, user='monitor', pw='xxx', db='monitor')
dict = dict(hostname=nodeName)
#nodes = db.select('Nodes', dict,where="hostName = $hostname")
nodes = db.query('SELECT * FROM Nodes') <-- I have tried both, but have comparable results (this returns more entries)
length = len(list(nodes))
print(length)
print(list(nodes))
print(list(nodes)[0])
下面是python的输出:
0.03 (1): SELECT * FROM Nodes
6 <-- Length is correct
[] <-- Why is this empty?
Traceback (most recent call last):
File "monitor.py", line 30, in <module>
print(list(nodes)[0]) <-- If it is empty I can't select first element
IndexError: list index out of range
下面是mySQL的输出:
mysql> select * from monitor.Nodes;
+--------+-------------+
| nodeId | hostName |
+--------+-------------+
| 1 | TestServer |
| 2 | raspberryPi |
| 3 | TestServer |
| 4 | TestServer |
| 5 | TestServer |
| 6 | TestServer |
+--------+-------------+
6 rows in set (0.00 sec)
结论:表包含条目,并且select/query语句能够获得它们的部分(它获得长度,但不是实际值?)
我已经尝试了多种方法,但目前我不能得到我想要的。我想从我的表中选择数据并在我的代码中使用它。
谢谢你的帮助
感谢reddit上的人们,我能够解决这个问题:https://www.reddit.com/r/learnpython/comments/53hdq1/webpy_select_returning_no_results_but_length_of/
底线是:查询方法的实现已经获取数据,因此第二次调用列表(节点)时数据已经消失,因此结果为空。
解决方案是将列表(节点)存储在一个变量中,并从该变量开始工作。