简体   繁体   English

使用SqlAlchemy的Select语句

[英]Select statement with SqlAlchemy

Yes, very basic question. 是的,非常基本的问题。 I've successfully created my db using declarative_base, and can perform inserts into the db too. 我已经使用declarative_base成功创建了数据库,并且也可以向数据库执行插入操作。 I just have a few questions about SqlAlchemy sql statements. 我只是对SqlAlchemy sql语句有几个问题。

I've create a table called Location. 我创建了一个名为Location的表。
A few issues/questions (see code below): 一些问题(请参见下面的代码):

  1. For statement, "print row", I have to specify each column name that I want to have output. 对于语句“打印行”,我必须指定要输出的每个列名称。 ie "print row.name, row.lat, etc" Why? 即“打印row.name,row.lat等”为什么? (Otherwise the print statement outputs "<classname.Location at <...>>" (否则,打印语句输出"<classname.Location at <...>>"

  2. Also, what is the preferred way to interact with a db and perform queries (select, insert, update, etc.)- there seem to be a bunch of options: using sqlalchemy.orm.select for example, or engine.text (<sql query>).execute().fetchall() , or even conn.execute(<select>). 此外,与数据库交互并执行查询(选择,插入,更新等)的首选方式是什么-似乎有很多选择:例如使用sqlalchemy.orm.select或engine.text (<sql query>).execute().fetchall() ,甚至conn.execute(<select>). Options are great, but right now they're all just confusing me. 选项很棒,但现在它们都让我感到困惑。

Thanks so much for the tips! 非常感谢您的提示!

Here's my code: 这是我的代码:

from sqlalchemy import create_engine
from sqlalchemy.sql import select
from location_db_setup import *

db_path = "sqlite:////volumes/users/shared/programming/python/web/map.db"
engine = create_engine(db_path, echo= True)
Session = sessionmaker(bind= engine)
session = Session()

session.query(Location).fetchall()
for row in locations:
        print row
  1. You code in sample is incomplete and has errors. 您的示例代码不完整,并且有错误。 So it's impossible to say for sure what is Location here. 因此,无法确定此处的Location是什么。 I assume it's a mapped class, so you are requesting a list of all Location objects , not rows . 我假设它是一个映射的类,所以您正在请求所有Location 对象的列表,而不是rows When you print an object you get its string representation. 当您打印对象时,将获得其字符串表示形式。 String representation of objects can be changed by defining custom __str__ method. 通过定义自定义__str__方法可以更改对象的字符串表示形式。
  2. Although ORM is the most important part of SQLAlchemy, it's not the only. 尽管ORM是SQLAlchemy最重要的部分,但不是唯一的。 It also expose a lot of functionality not related to ORM directly. 它还公开了许多与ORM直接不相关的功能。 When you work with objects the preferred way to create queries are corresponding session method. 使用对象时,创建查询的首选方法是相应的会话方法。 But sometimes you need selectable objects not bound to particular session (they are not executed directly, but are used in expressions passed to session methods). 但是有时您需要不绑定到特定会话的可选对象(它们不直接执行,而是在传递给会话方法的表达式中使用)。 That's why there are functions in sqlalchemy.orm package. 这就是sqlalchemy.orm包中包含函数的原因。

The preferred way to interact with a db when using an ORM is not to use queries but to use objects that correspond to the tables you are manipulating, typically in conjunction with the session object. 使用ORM时,与db进行交互的首选方法是不使用查询,而是使用与要操作的表相对应的对象,通常将其与会话对象结合使用。 SELECT queries become get() or find() calls in some ORMs, query() calls in others. SELECT查询在某些ORM中成为get()或find()调用,在其他ORM中成为query()调用。 INSERT becomes creating a new object of the type you want (and maybe explicitly adding it, eg session.add() in sqlalchemy). INSERT会创建所需类型的新对象(并且可能会显式添加它,例如sqlalchemy中的session.add())。 UPDATE becomes editing such an object, and DELETE becomes deleting an object (eg. session.delete() ). UPDATE成为编辑这样的对象,而DELETE成为删除对象(例如session.delete())。 The ORM is meant to handle the hard work of translating these operations into SQL for you. ORM旨在为您处理将这些操作转换为SQL的艰巨工作。

Have you read the tutorial ? 你看过教程了吗?

Denis and Kylotan gave you good answers. Denis和Kylotan给了您很好的答案。 I'm just gonna focus on point 2. 我只关注第二点。

Sometimes depends on your taste. 有时取决于您的口味。 There are times when you need database specific features that an ORM can't do, that's a case when you should use Session(<sql here>).execute() or conn.execute(<sql here>) . 有时候,您需要ORM无法完成的数据库特定功能,在这种情况下,您应该使用Session(<sql here>).execute()conn.execute(<sql here>) Another case is when you have a very complex query which is beyond you and you don't find a suitable ORM expression. 另一种情况是,您遇到了非常复杂的查询,而您又找不到合适的ORM表达式。

Usually, using ORM features like select([...]).where(... or Session.query(<Model here>).filter(... (declarative base) are enough. Almost every sql query has an ORM equivalent. 通常,使用select([...]).where(...Session.query(<Model here>).filter(... (声明性基数))之类的ORM功能就足够了。几乎每个sql查询都有一个ORM当量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM