是否可以在 SQLite 中存储 Python 类对象? [英] Is it possible to store Python class objects in SQLite?

查看:60
本文介绍了是否可以在 SQLite 中存储 Python 类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Python 对象存储到 SQLite 数据库中.这可能吗?

I would like to store Python objects into a SQLite database. Is that possible?

如果是这样,它的一些链接/示例是什么?

If so what would be some links / examples for it?

推荐答案

您不能将对象本身存储在数据库中.您所做的是存储来自对象的数据并在以后重建它.

You can't store the object itself in the DB. What you do is to store the data from the object and reconstruct it later.

一个好方法是使用优秀的 SQLAlchemy 库.它允许您将定义的类映射到数据库中的表.每个映射的属性都将被存储,并可用于重建对象.查询数据库会返回您的类的实例.

A good way is to use the excellent SQLAlchemy library. It lets you map your defined class to a table in the database. Every mapped attribute will be stored, and can be used to reconstruct the object. Querying the database returns instances of your class.

有了它,您不仅可以使用 sqlite,还可以使用大多数数据库 - 目前它还支持 Postgres、MySQL、Oracle、MS-SQL、Firebird、MaxDB、MS Access、Sybase、Informix 和 IBM DB2.而且您可以让您的用户选择她想要使用的数据库,因为您基本上可以在这些数据库之间切换,而无需更改代码.

With it you can use not only sqlite, but most databases - It currently also supports Postgres, MySQL, Oracle, MS-SQL, Firebird, MaxDB, MS Access, Sybase, Informix and IBM DB2. And you can have your user choose which one she wants to use, because you can basically switch between those databases without changing the code at all.

还有很多很酷的功能——比如自动JOINs、多态...

There are also a lot of cool features - like automatic JOINs, polymorphing...

一个快速、简单的例子,你可以运行:

A quick, simple example you can run:

from sqlalchemy import Column, Integer, Unicode, UnicodeText, String
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from random import choice
from string import letters

engine = create_engine('sqlite:////tmp/teste.db', echo=True)
Base = declarative_base(bind=engine)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(40))
    address = Column(UnicodeText, nullable=True)
    password = Column(String(20))

    def __init__(self, name, address=None, password=None):
        self.name = name
        self.address = address
        if password is None:
            password = ''.join(choice(letters) for n in xrange(10))
        self.password = password

Base.metadata.create_all()

Session = sessionmaker(bind=engine)
s = Session()

然后我可以这样使用它:

Then I can use it like this:

# create instances of my user object
u = User('nosklo')
u.address = '66 Some Street #500'

u2 = User('lakshmipathi')
u2.password = 'ihtapimhskal'

# testing
s.add_all([u, u2])
s.commit()

这将对数据库运行 INSERT 语句.

That would run INSERT statements against the database.

# When you query the data back it returns instances of your class:

for user in s.query(User):
    print type(user), user.name, user.password

该查询将运行 SELECT users.id AS users_id, users.name AS users_name, users.address AS users_address, users.password AS users_password.

打印结果为:

<class '__main__.User'> nosklo aBPDXlTPJs
<class '__main__.User'> lakshmipathi ihtapimhskal

因此,您可以有效地将对象存储到数据库中,这是最好的方式.

So you're effectively storing your object into the database, the best way.

这篇关于是否可以在 SQLite 中存储 Python 类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆