【问题标题】:Python - NULL data causing keyerror on DB INSERTPython - NULL 数据导致 DB INSERT 上的 keyerror
【发布时间】:2020-01-22 00:30:46
【问题描述】:

以下是我用于将 json 插入数据库的代码

list=result['intervalsDataPoints']
                for item in list:

                    if item['dataPoints'] !=[]:
                        result=item['dataPoints']
                        #print(result)

                        #print('hello')

                        for element in result:

                            dt = datetime.datetime.now()
                            #element["dt"] = dt
                            #element["epic"]=epic
                            #print(element)
                            #print(element['openPrice']['bid'])
                            print(element['timestamp'])
                            date_timestamp = datetime.datetime.fromtimestamp(element['timestamp']/1000)
                            cursor.execute("""INSERT INTO market_data_historic VALUES('%s','%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT ON CONSTRAINT UNIQUE_history DO NOTHING"""%(dt,epics,date_timestamp,element['openPrice']['bid'],element['openPrice']['ask'],element['closePrice']['bid'],element['closePrice']['ask'],element['highPrice']['bid'],element['highPrice']['ask'],element['lowPrice']['bid'],element['lowPrice']['ask'],element['lastTradedVolume']))
                            #cursor.executemany("""INSERT INTO market_data_historic(created_at,epic,timestamp,openprice_bid,openprice_close,closeprice_bid,closeprice_ask,highprice_bid,highprice_ask,lowprice_bid,lowprice_ask,last_traded_volume) VALUES (%(dt)s,%(epic)s,%(timestamp)s,%(openPrice['bid'])s,%(openPrice['close'])s,%(closePrice['bid'])s,%(closePrice['ask'])s,%(highPrice['bid'])s,%(highPrice['ask'])s,%(lowPrice['bid'])s,%(lowPrice['ask'])s,%(lastTradedVolume)s);""",element)
                            conn.commit()
                            #print(item)

但是,有些项目可能是 NULL,这会导致我的插入语句中断,从而导致此错误:

    cursor.execute("""INSERT INTO market_data_historic VALUES('%s','%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT ON CONSTRAINT UNIQUE_history DO NOTHING"""%(dt,epics,date_timestamp,element['openPrice']['bid'],element['openPrice']['ask'],element['closePrice']['bid'],element['closePrice']['ask'],element['highPrice']['bid'],element['highPrice']['ask'],element['lowPrice']['bid'],element['lowPrice']['ask'],element['lastTradedVolume']))
KeyError: 'bid'

我尝试在每个元素的末尾附加或 NONE,这样查询:

cursor.execute("""INSERT INTO market_data_historic VALUES('%s','%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT ON CONSTRAINT UNIQUE_history DO NOTHING"""%(dt,epics,date_timestamp,element['openPrice']['bid'] or None,element['openPrice']['ask'] or None,element['closePrice']['bid'] or None,element['closePrice']['ask'] or None,element['highPrice']['bid'] or None,element['highPrice']['ask'] or None,element['lowPrice']['bid'] or None,element['lowPrice']['ask'] or None,element['lastTradedVolume'] or None))

仍然没有运气! 你们如何建议我在上面的代码中考虑 NONE/NULL 值

【问题讨论】:

    标签: python json postgresql


    【解决方案1】:

    每当你试图访问python字典中某个键的值时,使用element['highPrice']['bid']这种方法,你必须确保该键存在,否则会触发异常。 如果您不确定密钥是否存在,则应使用以下内容:

    element['highPrice'].get('bid')  
    

    这不会引发异常,如果密钥不存在,它将默认返回 None。如果键不存在,您还可以提供您希望的返回值,如下所示:

    element['highPrice'].get('bid', 'value')
    

    这里需要注意的是,我假设您始终可以使用“highPrice”键。如果不是相同的逻辑,使用 .get 也应该在那里应用。 https://www.tutorialspoint.com/python/dictionary_get.htm

    【讨论】:

    • 您好刚刚尝试看到错误:psycopg2.errors.UndefinedColumn: column "none" does not exist LINE 1: ...1.982000','CC.D.LCO.USS.IP',' 2019-11-07 23:00:00',无,无,...
    • 嗨,这对我来说看起来很奇怪,在您发布的查询中,您没有指定列名,我相信任何 None 值都应该是列的值。确保没有动态提取列名,因为这不起作用。甚至可以尝试在查询中指定列名并尝试一些调试。
    • 感谢您回复 Dimitra。我已经按照你的建议做了:(“”“INSERT INTO market_data_historic(created_at,epic,timestamp,openprice_bid,openprice_ask,closeprice_bid,closeprice_ask,highprice_bid,highprice_ask,lowprice_bid,lowprice_ask,last_traded_volume) VALUES - 仍然看到同样的错误
    • 由于这不是别人可以真正复制的东西,我只能给你一些建议来帮助你确定真正的问题在哪里。首先,执行一个您知道它有效的静态插入查询,并从脚本内部测试它是否成功。然后,为了调试您的查询,在执行之前将查询创建分配给一个变量并打印出来。这样您就可以获得查询并将其直接应用于数据库。也许有些列不能为 Null,也许有些数据没有到达正确的列。您需要使用脚本生成的数据来分析查询。
    • Dimitra Paraskevopoulou 非常感谢您的帮助,我完全按照您的建议打印查询以进行调试。原来 NONE 不在 PostgresSQL 有问题的引号中。再次感谢!
    猜你喜欢
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多