【发布时间】:2017-09-16 13:56:27
【问题描述】:
我已经完成了SQLAlchemy ORM tutorial 的工作,现在正在将其调整到我自己的数据库中。我在尝试查询 Session 对象时遇到了 Postgres 方言的问题,但是我没有收到结果。我确信我错过了一些东西,并且可以使用一些方向来让它发挥作用,或者至少我应该研究什么。感谢您的帮助。
代码
import sqlalchemy
from sqlalchemy import create_engine, ForeignKey, Column, INTEGER
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import TEXT, NUMERIC, TIMESTAMP
from sqlalchemy.orm import sessionmaker
# CONNECTING
# create an instance of Engine, represents core interface to the db
engine = create_engine('postgresql://user:pass@ip:port/db', echo=True)
# DECLARE A MAPPING
# instantiate the Declarative base class for a catalog of classes & tables
# relative to the base class.
Base = declarative_base()
# map a table to a class by inheriting base class via declarative_base
class History_1m(Base):
__tablename__ = 'history_1m'
id = Column(INTEGER, primary_key=True, autoincrement=True)
name = Column(TEXT)
symbol = Column(TEXT)
ask = Column(NUMERIC)
bid = Column(NUMERIC)
# CREATE A SCHEMA
# using the engine, create our table via a method of the MetaData registry
Base.metadata.create_all(engine)
# CREATE AN INSTANCE OF MAPPED CLASS
# instantiate an instance of the User class and generate attribute values
symbol_data = History_1m()
# CREATING A SESSION
# define a Session class to talk with our db
Session = sessionmaker(bind=engine)
session = Session()
# in case of no engine yet, Session = sessionmaker() is acceptable
# to talk to the db you should use session = Session each time
# query the Session to verify the instance is pending
symbol = 'AAPL'
recent_symbol = session.query(History_1m).filter_by(symbol=symbol).first()
# print the contents of our_user, ed_user is our_user via identity map
print('\n> Do we have a symbol entry?\n', recent_symbol)
for row in session.query(History_1m).order_by(History_1m.id):
print(row.name, row.symbol, row.ask, row.bid)
追溯
Microsoft Corporation MSFT 65.52 65.51
Adobe Systems Incorporated ADBE 131.85 131.83
Cytori Therapeutics Inc CYTX 1.04 1.03
Whole Foods Market, Inc. WFM 35.58 35.57
None None None None
进程以退出代码 0 结束
【问题讨论】:
-
目前尚不清楚您从哪里获得
NameError。你的例子不应该产生它。请同时包含verifiable example 和您获得的回溯。或者重写你的标题和问题。至于获取None,您确定您的数据库包含name = 'AAPL'的行,还是您的意思是filter_by(symbol=symbol)?您是否连接到正确的数据库? -
您好 Ilja,我已将问题重新命名,并将输出部分更改为 Traceback。我知道我正在连接到正确的数据库。我相信您在我寻找符号而不是名称字段的地方是正确的。
-
不完全确定您所说的“在将 symbol_data 添加到会话并对其进行查询之前,我必须为其创建映射类的实例吗?”,
symbol_data = History_1m()是多余的,因为您不会将其添加到会话中。它只是绑定到名称 symbol_data 的History_1m类的一个新的未使用实例,没什么特别的。回溯是您与异常一起获得的输出,并包含堆栈跟踪等。我要求它,因为您的原始标题暗示了异常。显然,您的原始查询的问题只是列错误(名称与符号)。 -
总而言之,我认为您应该仔细阅读本教程,因为您似乎对术语和什么是什么感到有些困惑。
-
谢谢,我明白你所说的 symbol_data 是多余的。我正在继续审查文档并取得良好进展。
标签: python postgresql session orm sqlalchemy