一、问题描述
最近在Python中查询数据库时,下述查询代码执行很慢,平均到达30多秒:
try:
t_origin_begin = time.time()
conn = self.poolsSta.connection()
cur = conn.cursor()
cur.execute(sql)
loger.info(sql)
rowset = cur.fetchall()
cur.close()
conn.close()
t_origin_end = time.time()
print 't_origin_fetch = ', (t_origin_end - t_origin_begin)
except Exception as e:
loger.error(u"数据库操作出错!" + e.message)
这里用到的sql为
select s.x, s.y, s.line_id, s.station_id, s.station_num, s.name, l.citys, l.name, l.key_name from bus_station_info s,bus_line_info l where l.type in('1','4','5','6','7','8','16','17') and l.line_id=s.line_id and l.front_name!=s.name and l.terminal_name!=s.name and s.point_type!='6' and s.del_status != '1' and s.status = '1' and l.status='1' and s.city in(021) limit 0 , 2919
二、问题解决
上述sql查询缓慢的问题出在最后一个查询条件s.city in(021)
上,city在数据库中的类型为varchar(10)
,而这里传入的参数为021
,是一个整数,传入的参数值和字段类型不匹配
,导致查询速度很慢,使程序运行运行总时长翻了4倍。
传值类型不匹配的问题在多线程环境中更为严重,尤其是查询条件中的字段是关键字段,或者为索引字段时。