我有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)
但是在这种情况下,我只收到了一个结果,我的下一个功能不起作用。哪里有错误?请帮忙。
答案 0 :(得分:0)
我不是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)