2017-04-15 66 views
0

我是一个新手,我坚持这个postgres插入步骤。编写python postgres插入命令的最佳方法

我的挑战是我从存储在列表中的json拉取字典,我试图从字典中提取值并将其保存到postgres数据库中。

如何正确地写这件事的任何帮助,将不胜感激

这里是页的分页线下的数据库连接字符串用于数据库插入代码。

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, ... 

我敢肯定,这是不正确等等任何帮助和指导都会很棒。

在此先感谢。

+0

请添加用于数据库连接的'import'。 – wildplasser

+0

我已经更新了这个信息 – Xander

+0

的第一篇文章,除了在几件事情(不需要分配所有这些L *变量)上“漫长的路程”之外,它对我来说看起来很好。它实际上工作吗?如果不是,哪些不起作用? –

回答

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]) 
+0

假设所有列都是字符串? –