"""
执行SQL,返回一个结果 或者多个结果组成的列表
"""
try:
if num > 100:
print "num can't big than 100"
return
engine = mysql.connector.connect(user=user, password=password, database=database, host=host, port=port)
cursor = engine.cursor()cursor.execute(sql, num,args)
d = cursor.fetchall()
vaules = d[0:num]
if cursor.description:
names = [x[0] for x in cursor.description]
return [Dict(names, x) for x in vaules]
finally:if cursor:
cursor.close()
定义了一个方法_select(),本意想封装一个方法,方便对mysql的方便操作:返回num条查询结果,但是发觉如果没有对查询结果全部取回的话,会报错:Unread result found,所以如果换成如下的代码就会抛出异常:
try:
if num > 100:
print "num can't big than 100"
return
engine = mysql.connector.connect(user=user, password=password, database=database, host=host, port=port)
cursor = engine.cursor()cursor.execute(sql, num,args)
#d = cursor.fetchall()
#vaules = d[0:num]
if cursor.description:
names = [x[0] for x in cursor.description]
return [Dict(names, x) for x in cursor.fetchmany(num)]
finally:if cursor:
cursor.close()
本文介绍了一种使用Python封装MySQL查询的方法,通过自定义函数实现指定数量的数据查询,并讨论了如何避免因未完全读取结果而导致的错误。
3846

被折叠的 条评论
为什么被折叠?



