Python MySQL 游标无法获取行

标签 python mysql mysql-python

我正在尝试从 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/

相关文章:

python - 为什么我看不到我的 LabelFrame?

php - 重构字母通配符语句

mysql - 使用二进制排序规则有什么影响?

python - 如何使用 Python 在 MySQL 数据库中存储 API 响应?

python - 如何将*列*列表传递给 MySQLDb 执行

python - 是否可以克隆请求以供以后使用?

python - 事件未定义?

python - 将鼠标事件函数与 tensorflow 一起用于对象检测时列出索引超出范围错误

compiler-construction - mac os 10.9.1 上的 mysql-python

MySQL:从表 'a.total' 的列 'a.name' 中的值 'b.content' 的计数中填充列 'b'