首页 > 解决方案 > api数据直接用python插入PostgreSQL数据库

问题描述

主文件

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/

错误通过

它会在这里改变时间戳类型,如果是的话,我必须使用哪种数据类型?56行发生了什么?

PGadmin 类型

标签: jsondatabasepython-3.xpostgresql

解决方案


我认为login_time应该是time without time zonePostgresSQL 的类型。

但是你可能会更好地使用timestamp with time zone一起表示日期和时间。


推荐阅读