于 2020 年 1 月 7 日更新
在上一篇文章中,我们看到了如何使用execute()方法执行 sql 查询。 execute()方法返回受影响的行,但不返回结果。 要获取结果,我们使用游标对象的fetchall()方法。
语法: cursor.fetchall()
成功后,它将返回行的元组,其中每一行都是一个元组。
from __future__ import print_functionimport MySQLdb as mydb = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()number_of_rows = cursor.execute("select * from city");result = cursor.fetchall()print(result)db.close()
上面的代码将打印城市表中的所有行。
您也可以使用for循环遍历结果。
from __future__ import print_functionimport MySQLdb as mydb = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()number_of_rows = cursor.execute("select * from city");result = cursor.fetchall()for row in result:print(row)db.close()
一些更多的例子。
示例 1:
from __future__ import print_functionimport MySQLdb as mydb = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()id = 10operation = ">"sql = "select * from city where id {} {}".format(operation, id)number_of_rows = cursor.execute(sql)result = cursor.fetchall()for row in result:print(row[0], row[1])db.close()
示例 2:
from __future__ import print_functionimport MySQLdb as mydb = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()city = "%pur%"sql = "select * from city where name like '{}'".format(city)number_of_rows = cursor.execute(sql)result = cursor.fetchall()for row in result:print(row[0], row[1])db.close()
在下一篇文章中,我们讨论如何将行插入数据库中。
