【问题标题】:Updating data in postgres using python API使用 python API 更新 postgres 中的数据
【发布时间】:2025-12-12 08:20:03
【问题描述】:
我有一个 python API,它访问一个 URL 并接收一个 JSON。有一个包含订单数据的表
Order_id ZipCode delivery_date total
API 返回的 json 包含正在传递的邮政编码所在的城市和州。
我想:
- 向表中添加新列
City and State
- 根据对应的邮政编码更新以上2列
如何通过python做到这一点?
【问题讨论】:
-
这是可以做到的。但是你必须自己写一些代码。如果您已经尝试过,但代码不起作用,请编辑您的问题并解释您尝试了什么,以及什么没有按预期工作。 How to Ask
标签:
python
json
postgresql
openstack-python-api
【解决方案1】:
您可以使用适配器首先建立与 python 的连接,例如 psycopg2 或 sqlalchemy
使用 psycopg2
import psycopg2
class Postgres(object):
"""docstring for Postgres"""
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
# normally the db_credenials would be fetched from a config file or the enviroment
# meaning shouldn't be hardcoded as follow
db_config = {'dbname': 'demo', 'host': 'localhost',
'password': 'postgres', 'port': 5432, 'user': 'postgres'}
try:
print('connecting to PostgreSQL database...')
connection = Postgres._instance.connection =
psycopg2.connect(**db_config)
cursor = Postgres._instance.cursor = connection.cursor()
cursor.execute('SELECT VERSION()')
db_version = cursor.fetchone()
except Exception as error:
print('Error: connection not established {}'.format(error))
Postgres._instance = None
else:
print('connection established\n{}'.format(db_version[0]))
return cls._instance
def __init__(self):
self.connection = self._instance.connection
self.cursor = self._instance.cursor
def write(self, query):
try:
self.cursor.execute(query)
except Exception as error:
print('error execting query "{}", error: {}'.format(query, error))
return None
def read(self, query):
try:
self.cursor.execute(query)
return self.cursor.fetchall()
except Exception as error:
print('error execting query "{}", error: {}'.format(query, error))
return None
else:
return result
def __del__(self):
self.connection.close()
self.cursor.close()
然后实例化 postgress 类,并调用 read 或 write 方法,给出目标是从数据库写入还是读取。