Python的ORM框架SQLAlchemy入门教程
程序员文章站
2022-04-27 22:05:43
...
SQLAlchemy的理念是,SQL数据库的量级和性能重要于对象集合;而对象集合的抽象又重要于表和行。
一 安装 SQLAlchemy
一 安装 SQLAlchemy
复制代码 代码如下:
pip install sqlalchemy
导入如果没有报错则安装成功
导入如果没有报错则安装成功
复制代码 代码如下:
>>> import sqlalchemy
>>> sqlalchemy.__version__
'0.9.1'
>>>
>>> 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) # 绑定元信息
>>>
(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_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>
(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=, primary_key=True, nullable=False), Column('name', VARCHAR(length=40), table=), Column('email', VARCHAR(length=120), table=), schema=None)
>>>
>>> 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=
>>>
实例化一个插入句柄
复制代码 代码如下:
>>> i = users_table.insert()
>>> i
>>> 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
>>> 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
>>>
>>> i = users_table.insert()
>>> i
>>> 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
>>> 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
>>>
数据库内容为
复制代码 代码如下:
sqlite> select * from users;
1|rsj217|rsj21@gmail.com
2|ghost|
3|test|
sqlite>
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) # 创建映射
>>> ul = User()
>>> ul.name
>>> print ul
User(None, None)
>>> print ul.name
None
>>>
>>> class User(object):
... def __repr__(self):
... return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.email)
...
>>> mapper(User, users_table) # 创建映射
>>> ul = User()
>>> ul.name
>>> print ul
User(None, None)
>>> print ul.name
None
>>>
建立会话
查询
复制代码 代码如下:
>>> session = create_session()
>>> session
>>> query = session.query(User)
>>> query
>>> 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'
>>>
>>> session = create_session()
>>> session
>>> query = session.query(User)
>>> query
>>> 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)
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
>>> u = User()
>>> u.name = 'new'
>>> session.add(u)
>>> session.flush()
>>> session.commit()
>>>
>>> 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)
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
>>> u = User()
>>> u.name = 'new'
>>> session.add(u)
>>> session.flush()
>>> session.commit()
>>>
注意建立会话的方式, sqlalchemy 的版本不同 sessionmaker 的方式更好
剩下删除 关系 事物等高级操作就参考官方文档了。
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
相关文章
相关视频
专题推荐
-
独孤九贱-php全栈开发教程
全栈 170W+
主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门
-
玉女心经-web前端开发教程
入门 80W+
主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门
-
天龙八部-实战开发教程
实战 120W+
主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习
上一篇: Oracle两个表连接的分段查询
下一篇: Python全栈之路系列之文件操作
推荐阅读
-
Python ORM框架SQLAlchemy学习笔记之数据查询实例
-
Python ORM框架SQLAlchemy学习笔记之映射类使用实例和Session会话介绍
-
Python ORM框架SQLAlchemy学习笔记之关系映射实例
-
详解Python的Django框架中manage命令的使用与扩展
-
Python的Django框架下管理站点的基本方法
-
盘点这 7 款 Python 开源框架的优缺点
-
我的第一个python web开发框架(31)——定制ORM(八)
-
Python实现手写一个类似django的web框架示例
-
Python的Flask框架中的signals信号机制
-
Go Web框架gin的入门教程
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论