我正在尝试将列添加到pyodbc中fetchall()方法返回的列表中,但是它给了我一个错误。这是我的代码:
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 shell中创建了一个代表性示例,它工作正常,但我手动创建了一个列表列表,而不是从fetchall()生成一个列表。如何解决此错误?
答案 0 :(得分: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]