【问题标题】:Does not work cursor function in python在python中不起作用光标功能
【发布时间】:2017-07-11 09:24:53
【问题描述】:

我有 python 脚本来获取从 sql 到 nginx 的域。

#!/usr/bin/python3

import MySQLdb

query = 'SELECT name_of_domain FROM domain_table'
database_connect = MySQLdb.connect(host=host, user=user, passwd=password, db=database, port=port)
cursor = database_connect.cursor()
cursor.execute(query)
while True:
    row = cursor.fetchone()
    print (row)

在这种情况下一切正常。在一个循环中,我逐行接收所有行。 我决定使用功能: 我的功能:

def get_cursor():
    database_connect = MySQLdb.connect(host=host, user=user, passwd=password, port=port, db=database, charset='utf8')
    database_connect.autocommit(True)
    return database_connect.cursor(MySQLdb.cursors.DictCursor)

我已经尝试过使用这个:

#!/usr/bin/python3

import MySQLdb

cursor = get_cursor()
query = 'SELECT name_of_domain FROM domain_table'
cursor.execute(query)
while True:
    row = cursor.fetchone()
    print (row)

但在这种情况下,我只收到一个结果,我的下一个功能不起作用。我哪里有错误?请帮忙。

【问题讨论】:

  • 你试过了吗:row = cursor.fetchmany(size=1)?
  • TypeError: unsupported operand type(s) for +: 'dict' and 'str'
  • 如果您将MySQLdb.cursors.DictCursor 放入有效的那个会发生什么?这会产生相同的行为吗?

标签: python mysql while-loop cursor


【解决方案1】:

我不是 100% 确定,但认为这是因为 cursor.execute() 返回一个迭代器,该迭代器被第一个 .fetchone() 调用用完。

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html

尝试替换

while True:
    row = cursor.fetchone()
    print (row)

for row in cursor:
    print(row)

【讨论】:

  • 对不起。它没有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 2015-01-29
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
相关资源
最近更新 更多