【问题标题】:How to point session.add() to a specific table如何将 session.add() 指向特定表
【发布时间】:2015-10-11 16:36:33
【问题描述】:

我正在尝试逐行遍历 csv 并使用 session.add 函数将数据插入到特定的 postgres 数据库和表中。

import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.url import URL

# Define database
DATABASE = {
    'drivername': 'postgresql',
    'host': 'localhost',
    'port': '5432',
    'username': 'postgres',
    'password': 'password',
    'database': 'postgres'
    }

# Connect to the database
return engine = create_engine(URL(DATABASE))

# Sessionmaker returns a class
session = sessionmaker(bind=engine)()

# Open csv
r = csv.reader(open("E:\Testcsv.csv"))

# Skip headers
r.next()

end = False
while end == False:
    try:
        next = r.next()
            tableupdate = (
            var_oid = next[0],
            var_trip_id = next[1],
            var_route_id = next[2],
            var_vehicle_id = next[3],
            var_position_latitude = next[4],
            var_position_longitude = next[5],
            var_timestamp = next[6]
            )

    except StopIteration:
        end = True

如何使用 session.add() 函数将数据添加到已定义的名为“vehicle_positions”的表中来完成此代码。

【问题讨论】:

    标签: postgresql python-2.7 sqlalchemy


    【解决方案1】:

    Sqlalchemy session.add() 适用于模型实例 (reference),因此如果您愿意使用 session.add(),只需将表与定义的模型 (sqlalchemy mapping table columns) 进行映射。

    如果您可以使用原始执行,您可以通过简单地使用 session.execute('insert into table ......') reference to use session.ececute() 来运行插入。

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 2021-05-21
      • 2013-10-08
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多