1

我正在尝试将一列添加到从 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() 生成列表。如何解决此错误?

4

1 回答 1

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]
于 2013-07-15T20:00:29.853 回答