【发布时间】:2019-07-23 01:44:25
【问题描述】:
我想将来自 API 的结果字典 INSERT 输入到我的数据库中,目前我可以一次插入一个项目。
这是我的代码:
import json
import requests
import psycopg2
def my_func():
response = requests.get("https://path/to/api/")
data = response.json()
while data['next'] is not None:
response = requests.get(data['next'])
data = response.json()
for item in data['results']:
try:
connection = psycopg2.connect(user="user",
password="user",
host="127.0.0.1",
port="5432",
database="mydb")
cursor = connection.cursor()
postgres_insert_query = """ INSERT INTO table_items (NAME) VALUES (%s)"""
record_to_insert = item['name']
cursor.execute(postgres_insert_query, (record_to_insert,))
connection.commit()
count = cursor.rowcount
print (count, "success")
except (Exception, psycopg2.Error) as error :
if(connection):
print("error", error)
finally:
if(connection):
cursor.close()
connection.close()
my_func()
所以,这个正在工作,但是例如,如果我想插入table_items,而不仅仅是在name 行,而是说,name, address, weight, cost_per_unit,从那个表,那么我将更改这些行代码:
postgres_insert_query = 'INSERT INTO table_items (NAME, ADDRESS, WEIGHT, COST_PER_UNIT) VALUES (%s,%s,%s,%s)'
record_to_insert = (item['name']['address']['weight']['cost_per_unit'])
然后它会抛出:
无法将记录插入 table_items 表字符串索引必须是整数 PostgreSQL 连接已关闭
我的意思是,第一个版本,只有一个字段可以完美运行,但我每次都需要插入其他 3 个字段,有什么想法吗?
【问题讨论】:
标签: python postgresql psycopg2