在烧瓶中使用SQL炼金术将数据插入Postgres

时间:2019-01-30 08:09:33

标签: python postgresql sqlalchemy flask-sqlalchemy

我正在从本地计算机,个人ID和个人名称传递到ubuntu服务器。然后将读取此信息并将其传递到数据库。我正在使用下面的代码,但是不知何故我无法完成它。我是所有这些的新手,所以不确定我缺少什么

@app.route("/personInformation", methods=['POST'])
def parsingData():

        data = request.get_json(force=True)
        personID = data['person_id']
        personName = data['person_name']

        import pandas as pd
        import sqlalchemy as sql
        import sqlalchemy.orm as orm         

        db=sql.create_engine(connectionString)            
        metadata = sql.schema.MetaData(bind=db,reflect=True)
        table = sql.Table('patient_all_info', metadata, autoload=True)

        class Row(object):
            pass
        rowmapper = orm.Mapper(Row,table)
        Sess = orm.sessionmaker(bind = db)
        session = Sess()
        row1 = Row() 
        row1.person_id = personID
        row1.person_name = personName
        session.add(row1)
        session.commit()
        return "sent, no error"

1 个答案:

答案 0 :(得分:0)

您可以尝试下面的结构吗?我从我的一个项目中改编了它。

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData

Base = declarative_base()
engine = create_engine(connstring)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()    
conn = engine.connect()    
metadata = MetaData()

SomeDataTable = Table('TableName', metadata,
    Column('Column1', Integer, primary_key=True),
    Column('Column2', String(250), nullable=False),
    schema = 'schema_name'
)

stmt = SomeDataTable.insert().values([{"Column1": 1},{"Column2": "test"}])
conn.execute(stmt)