python操作mysql 抛出Unread result found的处理方法

来源:互联网 发布:网络大电影的宣传 编辑:程序博客网 时间:2024/06/06 20:18
def _select(sql, num, *args):
    """
    执行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()




0 0
原创粉丝点击