Python select 使用 _mysql 模块没有错误

Python select with _mysql module without an error

我需要使用 _mysql,但我不知道如何正确获取我选择的所有输出。

db = sql.connect(host=host,user=user,passwd=pw,db=dbName)
db.query(query)
rows = db.use_result()
while rows:
    result = rows.fetch_row()[0]
    print result

使用这段代码我得到了所有的数据,还有这个:

 result = rows.fetch_row()[0]
IndexError: tuple index out of range

当我使用 db.store_result 时,同样的事情发生了。

如何得到所有的输出而不出错?

编辑: 我的问题是,这段时间 运行 没完没了。 那么我怎么知道是否没有更多的结果行呢?

可能的解决方案:

 while 1:
     result = rows.fetch_row()
     if result:
         print result[0]
     else:
         break

你有什么更好的主意吗?

尝试从 result = rows.fetch_row()[0] 中删除 [0],例如 result = rows.fetch_row()

已编辑:

db = sql.connect(host=host,user=user,passwd=pw,db=dbName)
cursor = db.cursor()
cursor.execute(query)
results = cursor.fetchall()
for result in results:
    print result[0]

更好的方法是:

while i < rows.num_rows():
    i+=1
    result = rows.fetch_row()[0]