欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python的ORM框架SQLAlchemy入门教程

程序员文章站 2023-11-03 21:26:10
sqlalchemy的理念是,sql数据库的量级和性能重要于对象集合;而对象集合的抽象又重要于表和行。一 安装 sqlalchemy复制代码 代码如下:pip instal...


sqlalchemy的理念是,sql数据库的量级和性能重要于对象集合;而对象集合的抽象又重要于表和行。

一 安装 sqlalchemy

复制代码 代码如下:
pip install sqlalchemy

导入如果没有报错则安装成功
复制代码 代码如下:
>>> import sqlalchemy
>>> sqlalchemy.__version__
'0.9.1'
>>>

二 使用 sqlalchemy对数据库操作

1. 定义元信息,绑定到引擎

复制代码 代码如下:

(env)ghost@ghost-h61m-s2v-b3:~/project/flask/fsql$ python
python 2.7.3 (default, apr 10 2013, 05:13:16)
[gcc 4.7.2] on linux2
type "help", "copyright", "credits" or "license" for more information.
>>> from sqlalchemy import *
>>> from sqlalchemy.orm import *
>>> engine = create_engine('sqlite:///./sqlalchemy.db', echo=true)  # 定义引擎
>>> metadata = metadata(engine) # 绑定元信息
>>>

2.创建表格,初始化数据库

复制代码 代码如下:

>>> users_table = table('users', metadata,
...     column('id', integer, primary_key=true),
...     column('name', string(40)),
...     column('email', string(120)))
>>>
>>> users_table.create()
2014-01-09 10:03:32,436 info sqlalchemy.engine.base.engine
create table users (
    id integer not null,
    name varchar(40),
    email varchar(120),
    primary key (id)
)

                                                 
2014-01-09 10:03:32,436 info sqlalchemy.engine.base.engine ()
2014-01-09 10:03:32,575 info sqlalchemy.engine.base.engine commit
>>>

执行上述代码,我们就创建 一个 users 表,有id, name, email 三个字段

复制代码 代码如下:

(env)ghost@ghost-h61m-s2v-b3:~/project/flask/fsql$ sqlite3 sqlalchemy.db
sqlite version 3.7.13 2012-06-11 02:05:22
enter ".help" for instructions
enter sql statements terminated with a ";"
sqlite> .tables
users
sqlite>

3. 基本操作,插入

如果已经table表已经存在, 第二次运行就不许要 create了,  使用 autoload 设置

复制代码 代码如下:

>>> from sqlalchemy import *
>>> from sqlalchemy.orm import *
>>> engine = create_engine('sqlite:///./sqlalchemy.db', echo=true)
>>> metadata = metadata(engine)
>>> users_table = table('users', metadata, autoload=true)
2014-01-09 10:20:01,580 info sqlalchemy.engine.base.engine pragma table_info("users")
2014-01-09 10:20:01,581 info sqlalchemy.engine.base.engine ()
2014-01-09 10:20:01,582 info sqlalchemy.engine.base.engine pragma foreign_key_list("users")
2014-01-09 10:20:01,583 info sqlalchemy.engine.base.engine ()
2014-01-09 10:20:01,583 info sqlalchemy.engine.base.engine pragma index_list("users")
2014-01-09 10:20:01,583 info sqlalchemy.engine.base.engine ()
>>> users_table
table('users', metadata(bind=engine(sqlite:///./sqlalchemy.db)), column('id', integer(), table=<users>, primary_key=true, nullable=false), column('name', varchar(length=40), table=<users>), column('email', varchar(length=120), table=<users>), schema=none)
>>>

实例化一个插入句柄

复制代码 代码如下:

>>> i = users_table.insert()
>>> i
<sqlalchemy.sql.dml.insert object at 0x31bc850>
>>> print i
insert into users (id, name, email) values (?, ?, ?)
>>> i.execute(name='rsj217', email='rsj21@gmail.com')
2014-01-09 10:24:02,250 info sqlalchemy.engine.base.engine insert into users (name, email) values (?, ?)
2014-01-09 10:24:02,250 info sqlalchemy.engine.base.engine ('rsj217', 'rsj21@gmail.com')
2014-01-09 10:24:02,251 info sqlalchemy.engine.base.engine commit
<sqlalchemy.engine.result.resultproxy object at 0x31bce10>
>>> i.execute({'name': 'ghost'},{'name': 'test'})
2014-01-09 10:24:57,537 info sqlalchemy.engine.base.engine insert into users (name) values (?)
2014-01-09 10:24:57,537 info sqlalchemy.engine.base.engine (('ghost',), ('test',))
2014-01-09 10:24:57,537 info sqlalchemy.engine.base.engine commit
<sqlalchemy.engine.result.resultproxy object at 0x31bcd50>
>>>

数据库内容为

复制代码 代码如下:

sqlite> select * from users;
1|rsj217|rsj21@gmail.com
2|ghost|
3|test|
sqlite>

查询 删除和插入类似 都需要先实例一个 sqlalchemy.sql.dml 对象

三 使用 orm

使用 orm 就是 将 python class 与 数据库的 table 映射,免去直接写 sql 语句

创建映射

复制代码 代码如下:

>>> class user(object):
...     def __repr__(self):
...             return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.email)
...
>>> mapper(user, users_table)  # 创建映射
<mapper at 0x31bcfd0; user>
>>> ul = user()
>>> ul.name
>>> print ul
user(none, none)
>>> print ul.name
none
>>>

建立会话


查询

复制代码 代码如下:

>>> session = create_session()
>>> session
<sqlalchemy.orm.session.session object at 0x31bef10>
>>> query = session.query(user)
>>> query
<sqlalchemy.orm.query.query object at 0x31bee50>
>>> u = query.filter_by(name='rsj217').first()
2014-01-09 10:44:23,809 info sqlalchemy.engine.base.engine select users.id as users_id, users.name as users_name, users.email as users_email
from users
where users.name = ?
 limit ? offset ?
2014-01-09 10:44:23,809 info sqlalchemy.engine.base.engine ('rsj217', 1, 0)
>>> u.name
u'rsj217'
>>>

插入

复制代码 代码如下:

>>> from sqlalchemy import *
>>> from sqlalchemy.orm import *
>>> engine = create_engine('sqlite:///./sqlalchemy.db')
>>> metadata = metadata(engine)
>>> users_table = table('users', metadata, autoload=true)
>>> class user(object): pass
...
>>> mapper(user, users_table)
<mapper at 0x18185d0; user>
>>> session = sessionmaker(bind=engine)
>>> session = session()
>>> u = user()
>>> u.name = 'new'
>>> session.add(u)
>>> session.flush()
>>> session.commit()
>>>

注意建立会话的方式, sqlalchemy 的版本不同 sessionmaker 的方式更好

剩下删除 关系 事物等高级操作就参考官方文档了。