api数据直接使用python插入PostgreSQL数据库

时间:2019-03-04 06:37:05

标签: json database python-3.x postgresql

main.py

import json, urllib.request, requests
import psycopg2
from psycopg2.extras import execute_values


# Retrieve Json Data from Within API

url = "https://datahead.herokuapp.com/api/employeers/"
response = urllib.request.urlopen(url)
data = json.loads(response.read())


# ***** connect to the db *******
try:
    conn = psycopg2.connect("dbname='datahead' user='postgres' host='localhost' password='datahead'")
except:
    print("I am unable to connect to the database")

# cursor
cur = conn.cursor()

fields = [
    'id', #integer
    'name', #varchar
    'log_date', #date
    'log_time', #timestamp
    'login', #timestamp
    'logout' #timestamp
]

for item in data:
    my_data = [item[field] for field in fields]
    insert_query = "INSERT INTO employee VALUES (%s, %s, %s, %s, %s, %s)"
    cur.execute(insert_query, tuple(my_data))
    conn.commit()

# close the cursor
cur.close()

# close the connection
conn.close()

请访问我的api数据格式https://datahead.herokuapp.com/api/employeers/

Error Through

它将更改此处的时间戳类型,如果是,那么我必须使用哪种数据类型? 第56行发生了什么事?

PGadmin type

1 个答案:

答案 0 :(得分:1)

我认为login_time在PostgresSQL中应为time without time zone类型。

但是最好使用timestamp with time zone一起表示日期和时间。