【发布时间】:2020-05-19 19:22:21
【问题描述】:
我对数据库和 API 还很陌生,但我想从 API 中检索 JSON 数据并使用 Python 将其存储在 PostgreSQL 数据库中。最终,我想将信息存储在数据库中,以便 TensorFlow 脚本使用。
我在这里查看了以前的问题,但似乎找不到有效的解决方案。如果有人可以提供任何进一步的信息或为我指明正确的方向,那就太好了。
到目前为止我有:
- 在我的 PostgreSQL 数据库中创建了一个表
- 检查与数据库的连接是否正常
- 检查正在读取的 JSON 数据
- 写了如下代码
import json, urllib.request, requests
import psycopg2
from psycopg2.extras import execute_values
# Retrieve Json Data from Within API
url = "https://api.exchangeratesapi.io/latest?symbols=USD,GBP"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
print(data)
# ***** connect to the db *******
try:
conn = psycopg2.connect(database='postgres', user='postgres', password='********', host='localhost', port='5432')
except:
print("I am unable to connect to the database")
# cursor
cur = conn.cursor()
fields = [
'USD',
'GBP',
'base',
]
for apidata in data:
my_data = [apidata[field] for field in fields]
insert_query = "INSERT INTO apidata VALUES (?, ?, ?)" #%d for int %s for string
cur.execute(insert_query, tuple(my_data))
conn.commit()
# close the cursor
cur.close()
# close the connection
conn.close()
【问题讨论】:
-
1.错误信息是什么? 2. api返回的json的典型格式是什么 3. 我认为你不需要将你的行设为元组,你可以在execute中显式地将每一行数据作为一个列表传递
-
嗨@Willyzekid,感谢您的回复。 1. 返回的错误信息是:C:\>python apisandbox.py {'rates': {'USD': 1.095, 'GBP': 0.89535}, 'base': 'EUR', 'date': '2020- 05-19'} 回溯(最后一次调用):文件“apisandbox.py”,第 81 行,在
my_data = [apidata[field] for field in fields] 文件“apisandbox.py”,第 81 行,在 my_data = [apidata[field] for field in fields] TypeError: string indices must be integers 2. 请看上面的JSON文件格式
标签: python json postgresql tensorflow