我正在尝试从 AWS MariaDB 获取数据:
cursor = self._cnx.cursor()
stmt = ('SELECT * FROM flights')
cursor.execute(stmt)
print(cursor.rowcount)
# prints 2
for z in cursor:
print(z)
# Does not iterate
row = cursor.fetchone()
# row is None
rows = cursor.fetchall()
# throws 'No result set to fetch from.'
我可以使用 MySQL Workbench 验证表是否包含数据。我错过了一些步骤吗?
编辑:关于 2 个答案:
res = cursor.execute(stmt)
# res is None
编辑:
我用一个文件创建了新的 Python 项目:
import mysql.connector
try:
cnx = mysql.connector.connect(
host='foobar.rds.amazonaws.com',
user='devuser',
password='devpasswd',
database='devdb'
)
cursor = cnx.cursor()
#cursor = cnx.cursor(buffered=True)
cursor.execute('SELECT * FROM flights')
print(cursor.rowcount)
rows = cursor.fetchall()
except Exception as exc:
print(exc)
如果我使用简单游标运行此代码,fetchall 会引发“没有可从中获取的结果集”。如果我使用缓冲游标运行,我可以看到游标的 _rows 属性包含我的数据,但 fetchall() 返回空数组。
最佳答案
你的问题是 cursor.execute(stmt)
返回一个包含结果的对象,而你没有存储它。
results = cursor.execute(stmt)
print(results.fetchone()) # 打印出来并弹出第一行
关于Python MySQL 游标无法获取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43643117/