-1
我已經通過了SQLAlchemy ORM tutorial,現在正在將它調整到我自己的數據庫。我遇到了Postgres方言的問題,我試圖查詢Session對象,但是我沒有收到結果。我相信我錯過了一些東西,並且可以利用一些方向來實現這個目標,或者至少我應該研究什麼。感謝您的幫助。SQLAlchemy如何從Session查詢對象獲取響應?
代碼
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:[email protected]: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'目前還不清楚。你的例子不應該產生它。請同時包含一個[可驗證的示例](http://stackoverflow.com/help/mcve)以及您獲得的回溯。或者重寫你的標題和問題。至於獲得'None',你確定你的數據庫包含一個'name ='AAPL'的行,或者你的意思是'filter_by(symbol = symbol)'?你是否連接到正確的數據庫? –
嗨Ilja,我重新命名了這個問題,並將輸出部分改爲Traceback。我知道我正在連接到正確的數據庫。我相信你是正確的,我正在尋找一個符號而不是名稱字段。 – Liquidgenius
在將symbol_data添加到會話並查詢它之前,是否必須爲symbol_data創建映射類的實例?如果是這樣,有沒有一種簡單的方法可以將它映射到表中的所有列,而不是在symbol_data對象中隱式定義它們? (如果這甚至是問題。) – Liquidgenius