0

我有一个 python API,它访问一个 URL 并接收一个 JSON。有一个包含订单数据的表

Order_id   ZipCode   delivery_date   total

API 返回的 json 包含正在传递的邮政编码的城市和州。

我想要 :

  • 向表中添加新列City and State
  • 根据对应的邮政编码更新上述2列

这如何通过 python 完成?

4

1 回答 1

0

您可以使用适配器首先建立与 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 给出如果目标是从数据库写入或读取。

于 2017-11-02T14:16:07.877 回答