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

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()




你可能感兴趣的:(python)