[英]Python / SQLalchemy - how to trigger a query?
我正在努力讓SQLalchemy通過python為我做一些任務。
我可以通過以下示例來實現它,但是我已經停留了一段時間,從for
循環移動查詢調用:
for instance in session.query(versions_table).filter(versions_table.c.version==Version):
並通過調用其中一個表結果獲得結果:
existingID = instance.id
(其中id
是返回表的PK)
我不能做的是找到一種隨意觸發查詢的方法,或者作為條件語句的結果,例如
if some conditions met:
do query
get / process result
我只能通過調用instance.fieldname
來獲取返回的值
任何人都可以指出我哪里出錯了,接受我對SQLalchemy函數的設置/調用方式並不十分滿意。
我想要做的是:
for instance in session.query(versions_table).filter(versions_table.c.version==Version):
if instance.id == True: #this is not correct
print instance.id
else:
print "no match"
更全面的腳本:
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql+mysqldb://u:p@localhost/sqlalchtest',
echo=False)
metadata = MetaData(bind=engine)
Session = sessionmaker(bind=engine)
versions_table = Table('versions', metadata, autoload=True)
def doVersionGet(sigfile_filename):
tree = etree.parse(sigfile_filename)
root = tree.getroot()
attributes = root.attrib
if 'DateCreated' in root.attrib:
DateCreated = (attributes["DateCreated"])
if 'Version' in root.attrib:
Version = (attributes["Version"])
doVersionPush(DateCreated,Version)
def doVersionPush(DateCreated,Version):
session = Session()
for instance in session.query(versions_table).filter(versions_table.c.version==Version):
existingID = instance.id
#this is not really what I want to do here any way, but this will fire the query every time
if __name__ == "__main__":
path = "location\sub_sig_files" ##home_subset for tests
for (path, dirs, files) in os.walk(path):
for file in files:
sigfile_filename = str(path)+"\\"+str(file)
doVersionGet(sigfile_filename)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.