2013-07-15 42 views
1

我想添加一列到从pyodbc中的fetchall()方法返回的列表,但它给我一个错误。这里是我的代码:将列添加到pyodbc列表

import pyodbc 
import time 
import calendar 
from datetime import date 

#variable declaration 
today = date.today() 
beginRange = date(today.year,today.month,1) 
endRange = date(today.year,today.month,2) #limit data to 2 days for testing 

#connect to database 
connJobDtl = pyodbc.connect("DSN=Global_MWM;UID=Master") 
cJobDtl = connJobDtl.cursor() 

#database query 
cJobDtl.execute("select job,suffix,seq,date_sequence,[...]") 
dataJobDtl = cJobDtl.fetchall() 
cJobDtl.close() 

#add another column to the list, date_sequence formatted to YYYY-MM 
dataJobDtl = [x + [x[3].strftime("%Y-%m")] for x in dataJobDtl] 

当我运行该脚本,我得到这个错误:

File "...\jobDetailScript.py", line 23, in <module> 
    dataJobDtl = [x + [x[3].strftime("%Y-%m")] for x in dataJobDtl] 
TypeError: unsupported operand type(s) for +: 'pyodbc.Row' and 'list' 

作为一个测试,我在Python壳创造了一个代表性的例子,它工作得很好,但我手动创建了列表列表,而不是从fetchall()生成列表。我该如何解决这个错误?

回答

1

它看起来相当简单 - 因为错误消息指出您正在尝试两种不同类型的对象。如果你只是把行列为列表,它应该可以工作,所以从我自己的临时测试中:

>>>cur.execute('<removed>') #one of my own tables 
>>>tmp = cur.fetchall() 
>>>type(tmp[0]) #this is KEY! You need to change the type 

<type 'pyodbc.Row'> 

>>>tt = [1,2,3] 
>>>tmp[0] + tt #gives the same error you have 

Traceback (most recent call last): 
    File "<pyshell#13>", line 1, in <module> 
tmp[0] + tt 
TypeError: unsupported operand type(s) for +: 'pyodbc.Row' and 'list' 

>>>list(tmp[0]) + tt #returns a list as you wanted 

[14520496, ..., 1, 2, 3] 
+0

这样做效果很好。感谢您的帮助! – emiller3061