Python错误:首先执行execute()

时间:2011-04-06 09:05:32

标签: python mysql django

当我尝试运行此视图/函数时,出现以下错误execute() first

def homepage(request, parem1, parem2):
    # open sql connection
    cursor = connection.cursor()

    if parem1 == 'p':

        if parem2 == 'all':   
            cursor.execute((" SELECT eventname, id, party, DATE_FORMAT(eventdate, GET_FORMAT(DATE,'EUR')) FROM mainapp_eventdetails ORDER BY eventdate DESC "))
        else:
            cursor.execute((" SELECT eventname, id, party, DATE_FORMAT(eventdate, GET_FORMAT(DATE,'EUR')) FROM mainapp_eventdetails WHERE party = '" + parem2 + "' ORDER BY eventdate DESC "))

    else:

        if parem2 == 'all':   
            cursor.execute((" SELECT eventname, id, party, DATE_FORMAT(eventdate, GET_FORMAT(DATE,'EUR')) FROM mainapp_eventdetails ORDER BY eventdate DESC "))
        elif parem2 == 'APR':
            cursor.execute((" SELECT eventname, id, party, DATE_FORMAT(eventdate, GET_FORMAT(DATE,'EUR')) FROM mainapp_eventdetails WHERE eventdate between '2011-4-1' AND '2011-5-1' ORDER BY eventdate DESC "))

    datalist = [memedetails for memedetails in cursor.fetchall()]

    # close sql connection
    cursor.close()
    connection.close()

    # group by eventdate
    datalistsorted = []

    # i dont like how this part depends on the sequence of columns retrieved in the above SQL. 
    for k, g in groupby(datalist, key=lambda x:x[3]):
        datalistsorted.append((k,[(i[0],i[1],i[2]) for i in g]))

    return render_to_response('base.html', {'eventlist': datalistsorted, 'parem2': parem2.upper()})

但如果我要将此行elif parem2 == 'APR':更改为else:,则可以正常使用。

为什么会这样,我怎样才能让elif工作? (下面有更多条件,但为了简单起见,我省略了它)

1 个答案:

答案 0 :(得分:3)

据推测,您遇到parem1不是'p'并且 parem2不是'APR'的情况。在这种情况下,您尚未执行任何调用。

也许您应该将if / else限制为仅定义要执行的字符串,并使用catch-all默认值,并在if块之外执行execute调用。