[英]Python data structures — do I need to use SQL plugin… if so, how?
I have the following class with associated attributes: 我有以下具有相关属性的类:
class Company(object):
self.ticker # string
self.company # string
self.creator # string
self.link # string
self.prices # list of tuples (this could be many hundreds of entries long)
self.creation_date # date entry
I populate individual companies and then store a list of companies into class Companies: 我填充各个公司,然后将公司列表存储到“公司”类中:
class Companies(object):
def __init__(self):
self.companies = []
def __len__(self):
return len(self.companies)
def __getitem__(self, key):
return self.companies[key]
def __repr__(self):
return 'Company list of length %i' % (self.__len__())
def add(self, company):
self.companies.append(company)
I want to be able to easily perform queries such as Companies.find(creator="someguy") and have the class return a list of all companies created by someguy. 我希望能够轻松地执行诸如Companies.find(creator =“ someguy”)之类的查询,并让该类返回someguy创建的所有公司的列表。 I also want to be able to run a query such as Companies.find(creation_date > x) and return a list of all entries created after a certain date. 我还希望能够运行诸如Companies.find(creation_date> x)之类的查询,并返回在特定日期之后创建的所有条目的列表。
I have a little bit of experience of doing similar work with Django's built in SQL functionality and found that to be pretty convenient. 我对使用Django的内置SQL功能进行类似的工作有一点经验,发现这样做非常方便。 However, this project isn't using Django and I don't know if there are any other, smaller packages that provide this functionality. 但是,该项目未使用Django,而且我不知道是否有其他较小的软件包可以提供此功能。 I'd like to keep the interfacing with the SQL server to a minimum because I don't have much experience with the language. 我想尽量减少与SQL Server的接口,因为我对这种语言没有太多的经验。
SQLAlchemy is a full featured Python ORM (Object Relational Mapper). SQLAlchemy是功能齐全的Python ORM(对象关系映射器)。 It can be found at http://www.sqlalchemy.org/ . 可以在http://www.sqlalchemy.org/上找到。
Example usage to define a new object: 定义新对象的用法示例:
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
To create a new User: 要创建一个新用户:
>>> ed_user = User('ed', 'Ed Jones', 'edspassword')
>>> ed_user.name
'ed'
>>> ed_user.password
'edspassword'
To write to the database (after creating a new session): 要写入数据库(在创建新会话之后):
ed_user = User('ed', 'Ed Jones', 'edspassword')
session.add(ed_user)
session.commit()
And to query: 并查询:
our_user = session.query(User).filter_by(name='ed').first()
>>> our_user
<User('ed','Ed Jones', 'edspassword')>
More details can be found at http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html (taken from docs). 可以在http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html (来自docs)中找到更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.