编写python postgres insert命令的最佳方法

时间:2017-04-15 14:04:15

标签: python json postgresql

我是一个新手,我坚持这个postgres插入步骤。

我的挑战是我从存储在列表中的json中提取Dict,并且我试图从dict中提取值并将其保存到postgres DB中。

任何有关如何正确编写此内容的帮助都将不胜感激

以下是分页行下DB的连接字符串是用于db insert的代码。

import psycopg2

'''DATABASE CONNECTION SETTINGS'''


def dbconnect():
    """Function returns settings for db connection."""
    dbauth = psycopg2.connect("dbname='databse' user='username' \
        host='dbhost' password='password'")

    return dbauth
def weatherupdate(dbauth, list):

connection = dbauth

try:
    connection
except:
    print "I am unable to connect to the database"

conn = connection
cursor = conn.cursor()

l01 = list[0]['state_time_zone']
l02 = list[0]['time_zone']
l03 = list[0]['product_name']
l04 = list[0]['state']
l05 = list[0]['refresh_message']
l06 = list[0]['name']
l11 = list[1]['swell_period']
l12 = list[1]['lat']
l13 = list[1]['lon']
l14 = list[1]['cloud_oktas']
l15 = list[1]['gust_kt']
l16 = list[1]['history_product']
l17 = list[1]['local_date_time']
l18 = list[1]['cloud']
l19 = list[1]['cloud_type']
l110 = list[1]['swell_height']
l111 = list[1]['wmo']
l112 = list[1]['wind_dir']
l113 = list[1]['weather']
l114 = list[1]['wind_spd_kt']
l115 = list[1]['rain_trace']
l116 = list[1]['aifstime_utc']
l117 = list[1]['press_tend']
l118 = list[1]['press']
l119 = list[1]['vis_km']
l120 = list[1]['sea_state']
l121 = list[1]['air_temp']
l122 = list[1]['cloud_base_m']
l123 = list[1]['cloud_type_id']
l124 = list[1]['swell_dir_worded']
l125 = list[1]['sort_order']

query = "INSERT INTO weather (state_time_zone, time_zone, product_name, state, refresh_message, name, swell_period, lat, lon, cloud_oktas, gust_kt, history_product, local_date_time, cloud, cloud_type, swell_height, wmo, wind_dir, weather, wind_spd_kt, rain_trace, aifstime_utc, press_tend, press, vis_km, sea_state, air_temp, cloud_base_m, cloud_type_id, swell_dir_worded, sort_order ) VALUES (l01, l02, l03, l04, l05, l06, l11, l12, l13, l14, l15, l16, l17, l18, l19, l110, l111, l112, l113, l114, l115, l116, l117, l118, l119, l120, l121, l122, l123, l124, l125);"

cursor.execute(query)

conn.commit()

weatherupdate(dbconnect(),getweather())

当我运行代码时,它会抛出此错误:

Traceback (most recent call last):
  File "weatherDb.py", line 57, in <module>
    weatherupdate(dbconnect(), getweather())
  File "weatherDb.py", line 53, in weatherupdate
    cursor.execute(query)
psycopg2.ProgrammingError: column "l01" does not exist
LINE 1: ...d_type_id, swell_dir_worded, sort_order ) VALUES (l01, l02, ...

我确定这是不正确的,所以任何帮助和方向都会很棒。

提前致谢。

1 个答案:

答案 0 :(得分:0)

query = """INSERT INTO weather (state_time_zone, time_zone, product_name, [SNIP]) 
            VALUES (%s, %s, %s, [SNIP] ) """
cursor.execute(query, (l01, l02, l03 [SNIP])