Python MySQLdb速度非常慢,结果集很大

Python MySQLdb速度非常慢,结果集很大,python,mysql-python,Python,Mysql Python,我在phpMyAdmin和MySQLdb(python)中执行了以下查询 phpMyAdmin说查询花费了2ms。 我的python代码说,使用MySQLdb进行查询需要848ms(甚至没有获取结果) python代码: self.db = MySQLdb.connect(host="localhost", user="root", passwd="", db="ibeat") self.cur = self.db.cursor() millis = lambda: time.time() *

我在phpMyAdmin和MySQLdb(python)中执行了以下查询

phpMyAdmin说查询花费了2ms。 我的python代码说,使用MySQLdb进行查询需要848ms(甚至没有获取结果)

python代码:

self.db = MySQLdb.connect(host="localhost", user="root", passwd="", db="ibeat")
self.cur = self.db.cursor()

millis = lambda: time.time() * 1000

start_time = millis()
self.cur.execute_cmd("""SELECT *, (SELECT CONCAT(`id`, '|', `name`, '|', `image_code`)
FROM `model_artist` WHERE `id` = `artist_id`) as artist_data, 
FIND_IN_SET("metallica", `searchable_words`) as find_0
FROM `model_song` HAVING find_0""")
print millis() - start_time

PHPMyAdmin对所有查询设置了限制,因此您不会在接口中返回大的结果集。因此,如果您的查询通常返回1000000行,而PHPMyAdmin将其减少到1000行(或者不管默认值是什么),那么当Python获取甚至查询整个结果集时,您将需要更长的处理时间


尝试在Python中设置一个与PHPMyAdmin的限制相比较的限制。

< P>如果你期望SQL查询有一个大的结果集,那么你就计划按记录迭代记录,那么你可能想考虑使用默认的游标来代替。默认游标将结果集存储在客户机中,而SSCursor将结果集存储在服务器中。与默认游标不同,如果只需逐个遍历记录,SSCursor将不会产生较大的初始延迟

您可以在上找到一些示例代码

例如,尝试:

import MySQLdb.cursors

self.db = MySQLdb.connect(host="localhost", user="root", passwd="", db="ibeat",
                          cursorclass = MySQLdb.cursors.SSCursor)

(其余的代码可以保持不变。)

如果在MySQL命令行上运行该查询,您会得到什么时间?返回多少条记录?你确定phpMyAdmin执行了查询吗?我想出来了,但没有看到你的答案。。。但是我会接受你的:POr如果你使用DictCursor,用SSDictCursor替换它,这样结果会作为字典列表返回。
import MySQLdb.cursors

self.db = MySQLdb.connect(host="localhost", user="root", passwd="", db="ibeat",
                          cursorclass = MySQLdb.cursors.SSCursor)