如何忽略" IndexError:列表索引超出范围"在SQL Execute Insert语句中

时间:2017-09-18 03:06:03

标签: python python-2.7 pyodbc pypyodbc

我正在使用Python 2.7从JSON API中提取数据并将其推送到SQL-Server表中。 我在将数据插入数据库时​​遇到问题,其中从JSON响应返回的某些条目缺少字典的一部分。 IE," CustomFields":90%的条目都有信息,但是10%没有,因此我得到索引错误 例如

"CustomFields":[
],

VS

"CustomFields":[
{
"Type":"foo",
"Name":"foo",
"Value":"foo"
},
{
"Type":"foo",
"Name":"foo",
"Value":"foo"
},
{
"Type":"foo",
"Name":"foo",
"Value":"foo"
},

我会改变什么,以便如果我得到一个缺失的索引,用'' NULL'条目进入数据库。

response = '*API URL*'
json_response = json.loads(urllib2.urlopen(response).read())

conn = pypyodbc.connect(r'Driver={SQL Server};Server=*Address*;Database=*DataBase*;Trusted_Connection=yes;')
conn.autocommit = False
c = conn.cursor()

c.executemany("INSERT INTO phil_targetproccess (ResourceType, Id, Name, StartDate, EndDate, TimeSpent, CreateDate, ModifyDate, LastStateChangeDate, ProjectName, EntityStateName, RequestTypeName, AssignedTeamMember#1, Area, SubArea, BusinessTeam) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ,
             [(x['ResourceType'],
               x['Id'],
               x['Name'],
               (parse_date(x['StartDate'])),
               (parse_date(x['EndDate'])),
               x['TimeSpent'],
               (parse_date(x['CreateDate'])),
               (parse_date(x['ModifyDate'])),
               (parse_date(x['LastStateChangeDate'])),
               x['Project']['Name'],
               x['EntityState']['Name'],
               x['RequestType']['Name'],
               y['GeneralUser']['FirstName']+' '+y['GeneralUser']['LastName'],
               x['CustomFields'][0]['Value'],
               x['CustomFields'][1]['Value'],
               x['CustomFields'][2]['Value'])
               for x in json_response['Items']
                  for y in x['Assignments']['Items']])

非常感谢。

3 个答案:

答案 0 :(得分:1)

我认为你的问题在这里

 x['CustomFields'][0]['Value'],
 x['CustomFields'][1]['Value'],
 x['CustomFields'][2]['Value']

当CustomFields没有元素时

尝试

 x['CustomFields'][0]['Value'] if len(x['CustomFields']) > 0 else '',
 x['CustomFields'][1]['Value'] if len(x['CustomFields']) > 1 else '',
 x['CustomFields'][2]['Value'] if len(x['CustomFields']) > 2 else '',

答案 1 :(得分:0)

您可以使用get方法检查是否value in CustomFields

如果是,则

可用,检查列表的长度,然后使用相同的get方法获取该列表中字典的值。

例如:

customfield_value = (x['CustomFields'][0]).get("Value",None) if len(x['CustomFields'])>0 else None

如果索引0中不存在该值,则返回None。您可以按照相同的方式获取其他2个索引的值。如果你不明白,请评论它将进一步解释。

答案 2 :(得分:0)

最终剧本。谢谢你的帮助!

   c.executemany("INSERT INTO phil_targetproccess (ResourceType, Id, Name, StartDate, EndDate, TimeSpent, CreateDate, "
          "ModifyDate, LastStateChangeDate, ProjectName, EntityStateName, RequestTypeName, AssignedTeamMember1, "
          "AssignedTeamMember2, AssignedTeamMember3, AssignedTeamMember4, Area, SubArea, BusinessTeam) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
          [(x['ResourceType'],
            x['Id'],
            x['Name'],
            (parse_date(x['StartDate'])),
            (parse_date(x['EndDate'])),
            x['TimeSpent'],
            (parse_date(x['CreateDate'])),
            (parse_date(x['ModifyDate'])),
            (parse_date(x['LastStateChangeDate'])),
            x['Project']['Name'],
            x['EntityState']['Name'],
            x['RequestType']['Name'],
            x['Assignments']['Items'][0]['GeneralUser']['FirstName'] + ' ' + x['Assignments']['Items'][0]['GeneralUser']['LastName'] if len(x['Assignments']['Items']) > 0 else None,
            x['Assignments']['Items'][1]['GeneralUser']['FirstName'] + ' ' + x['Assignments']['Items'][1]['GeneralUser']['LastName'] if len(x['Assignments']['Items']) > 1 else None,
            x['Assignments']['Items'][2]['GeneralUser']['FirstName'] + ' ' + x['Assignments']['Items'][2]['GeneralUser']['LastName'] if len(x['Assignments']['Items']) > 2 else None,
            x['Assignments']['Items'][3]['GeneralUser']['FirstName'] + ' ' + x['Assignments']['Items'][3]['GeneralUser']['LastName'] if len(x['Assignments']['Items']) > 3 else None,
            x['CustomFields'][0]['Value'] if len(x['CustomFields']) > 0 else '',
            x['CustomFields'][1]['Value'] if len(x['CustomFields']) > 1 else '',
            x['CustomFields'][2]['Value'] if len(x['CustomFields']) > 2 else '')
           for x in json_response['Items']])