Python SQLAlchemy - 无法访问SELECT语句结果的主键列

时间:2017-05-27 03:29:49

标签: python sqlalchemy

s = select([stations.c.name]).where(stations.c.name == station_name)
stations = connection.execute(s).fetchone()

我有上面的代码在SQL表上运行SELECT。但是,虽然可以访问匹配条目的其他列,但尝试通过电台[' id']访问其主键列时会出现错误:

"Could not locate column in row for column 'id'"

为什么?

表格定义:

stations = Table('stations', metadata,
        Column('id', Integer, primary_key = True),
        Column('name', String(16), nullable = False)
        )

1 个答案:

答案 0 :(得分:3)

注意:您应避免为不同的对象指定相同的名称,因为在您的情况下,在声明之后

 stations = connection.execute(s).fetchone()

初始stations Table对象不再可访问。您可以将提取的对象重命名为station_record,或将stations Table对象重命名为stations_table,或两者都重命名。

答案

如果你想获得一条记录的id,那么你应该查询它:

s = select([stations.c.id, stations.c.name]).where(stations.c.name == station_name)

s = select(stations.columns).where(stations.c.name == station_name)

最后我们可以有像

这样的东西
from sqlalchemy import MetaData, Table, Column, Integer, String, create_engine, select

db_uri = 'sqlite://'
engine = create_engine(db_uri)
metadata = MetaData(bind=engine)
stations = Table('stations', metadata,
                 Column('id', Integer, primary_key=True),
                 Column('name', String(16), nullable=False)
                 )
stations.create(checkfirst=True)
connection = engine.connect()
station_name = 'sample text'
connection.execute(stations.insert().values(name=station_name))
s = select(stations.columns).where(stations.c.name == station_name)
station_record = connection.execute(s).fetchone()
station_record_id = station_record['id']
station_record_name = station_record['name']
相关问题