'long'对象没有属性'fetchall'

时间:2014-02-06 10:28:39

标签: python django

我不知道这段代码有什么问题;以前它工作正常,但在数据库迁移(sqlite3到MySQL)后它不再有效。 (我正在使用MySQL)。

回溯:     在get_response中输入文件“/usr/lib/python2.6/site-packages/django/core/handlers/base.py”       111. response = callback(request,* callback_args,** callback_kwargs)     _wrapped_view中的文件“/usr/lib/python2.6/site-packages/django/contrib/auth/decorators.py”       23. return view_func(request,* args,** kwargs)

代码:

cursor = connection.cursor()            
    data = cursor.execute(query)
    data_list = data.fetchall()
    return redirect("http://www.example.com?code=123" , code=302)
    result_count = len(data_list)           
    if result_count==0:
        return HttpResponse('<script type="text/javascript"> alert ("try again"); window.location.href = "/reports/custom/";</script>')
    data_desc = data.description

    j=0
    """
        prepare first response  
    """
    now = datetime.datetime.now().strftime('%m-%d-%Y_%H:%M:%S')            
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=hiv_report_%s.csv' % now         
    writer = csv.writer(response)

    headers = []
    tab_no = 0
    for i in data_desc:
        #ws.write(0, j, (i[0].replace('_', ' ')).upper())                
        if i[0] == 'id':
            table_name = tab_order[tab_no]
            tab_no = tab_no +1

        headers.append((table_name+ " | " +i[0].replace('_', ' ')).upper())   

    writer.writerow(headers)
    """
        fill data into csv cells
    """            
    for value in data_list:
        k=0
        no_record_check=1                
        row = []
        for val in value:
            #ws.write(j, k, val)
            row.append(val)
        writer.writerow(row) 

1 个答案:

答案 0 :(得分:5)

MySQLdb.cursor.execute(query)返回一个包含返回行数的整数。数字对象没有fetchall方法。您需要在fetchall上调用cursor方法:

data_list = cursor.fetchall()

引用Python DB API

.execute(operation [, parameters])
Prepare and execute a database operation (query or command).
[...]
Return values are not defined.

正如Martijn在评论中所说sqlite3.cursor.execute返回光标。 由于DB API cursor.execute未定义MySQLdb.cursor.execute的返回值,因此可以返回任何内容(库编写者选择返回多行)。

这意味着使用Python DB API的可移植方法是忽略cursor.execute的返回值。