原文: https://thepythonguru.com/fetching-results/


    于 2020 年 1 月 7 日更新


    在上一篇文章中,我们看到了如何使用execute()方法执行 sql 查询。 execute()方法返回受影响的行,但不返回结果。 要获取结果,我们使用游标对象的fetchall()方法。

    语法cursor.fetchall()

    成功后,它将返回行的元组,其中每一行都是一个元组。

    1. from __future__ import print_function
    2. import MySQLdb as my
    3. db = my.connect(host="127.0.0.1",
    4. user="root",
    5. passwd="",
    6. db="world"
    7. )
    8. cursor = db.cursor()
    9. number_of_rows = cursor.execute("select * from city");
    10. result = cursor.fetchall()
    11. print(result)
    12. db.close()

    上面的代码将打印城市表中的所有行。

    您也可以使用for循环遍历结果。

    1. from __future__ import print_function
    2. import MySQLdb as my
    3. db = my.connect(host="127.0.0.1",
    4. user="root",
    5. passwd="",
    6. db="world"
    7. )
    8. cursor = db.cursor()
    9. number_of_rows = cursor.execute("select * from city");
    10. result = cursor.fetchall()
    11. for row in result:
    12. print(row)
    13. db.close()

    一些更多的例子。

    示例 1

    1. from __future__ import print_function
    2. import MySQLdb as my
    3. db = my.connect(host="127.0.0.1",
    4. user="root",
    5. passwd="",
    6. db="world"
    7. )
    8. cursor = db.cursor()
    9. id = 10
    10. operation = ">"
    11. sql = "select * from city where id {} {}".format(operation, id)
    12. number_of_rows = cursor.execute(sql)
    13. result = cursor.fetchall()
    14. for row in result:
    15. print(row[0], row[1])
    16. db.close()

    示例 2

    1. from __future__ import print_function
    2. import MySQLdb as my
    3. db = my.connect(host="127.0.0.1",
    4. user="root",
    5. passwd="",
    6. db="world"
    7. )
    8. cursor = db.cursor()
    9. city = "%pur%"
    10. sql = "select * from city where name like '{}'".format(city)
    11. number_of_rows = cursor.execute(sql)
    12. result = cursor.fetchall()
    13. for row in result:
    14. print(row[0], row[1])
    15. db.close()

    在下一篇文章中,我们讨论如何将行插入数据库中。