python的orm框架sqlalchemy入门教程
2016-06-17来源:

sqlalchemy是python操作数据库的一个库。能够进行orm映射,sqlalchemy“采用简单的python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型”

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

一安装sqlalchemy

代码如下:

pipinstallsqlalchemy

导入如果没有报错则安装成功

代码如下:>>>importsqlalchemy

>>>sqlalchemy.__version__

'0.9.1'

>>>

二使用sqlalchemy对数据库操作

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

代码如下:

(env)ghost@ghost-h61m-s2v-b3:~/project/flask/fsql$python

python2.7.3(default,apr102013,05:13:16)

[gcc4.7.2]onlinux2

typehelp,copyright,creditsorlicenseformoreinformation.

>>>fromsqlalchemyimport*

>>>fromsqlalchemy.ormimport*

>>>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-0910:03:32,436infosqlalchemy.engine.base.engine

createtableusers(

idintegernotnull,

namevarchar(40),

emailvarchar(120),

primarykey(id)

)

2014-01-0910:03:32,436infosqlalchemy.engine.base.engine()

2014-01-0910:03:32,575infosqlalchemy.engine.base.enginecommit

>>>

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

代码如下:

(env)ghost@ghost-h61m-s2v-b3:~/project/flask/fsql$sqlite3sqlalchemy.db

sqliteversion3.7.132012-06-1102:05:22

enter.helpforinstructions

entersqlstatementsterminatedwitha;

sqlite>.tables

users

sqlite>

3.基本操作,插入

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

代码如下:

>>>fromsqlalchemyimport*

>>>fromsqlalchemy.ormimport*

>>>engine=create_engine('sqlite:///./sqlalchemy.db',echo=true)

>>>metadata=metadata(engine)

>>>users_table=table('users',metadata,autoload=true)

2014-01-0910:20:01,580infosqlalchemy.engine.base.enginepragmatable_info(users)

2014-01-0910:20:01,581infosqlalchemy.engine.base.engine()

2014-01-0910:20:01,582infosqlalchemy.engine.base.enginepragmaforeign_key_list(users)

2014-01-0910:20:01,583infosqlalchemy.engine.base.engine()

2014-01-0910:20:01,583infosqlalchemy.engine.base.enginepragmaindex_list(users)

2014-01-0910:20:01,583infosqlalchemy.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.insertobjectat0x31bc850>

>>>printi

insertintousers(id,name,email)values(?,?,?)

>>>i.execute(name='rsj217',email='rsj21@gmail.com')

2014-01-0910:24:02,250infosqlalchemy.engine.base.engineinsertintousers(name,email)values(?,?)

2014-01-0910:24:02,250infosqlalchemy.engine.base.engine('rsj217','rsj21@gmail.com')

2014-01-0910:24:02,251infosqlalchemy.engine.base.enginecommit

<sqlalchemy.engine.result.resultproxyobjectat0x31bce10>

>>>i.execute({'name':'ghost'},{'name':'test'})

2014-01-0910:24:57,537infosqlalchemy.engine.base.engineinsertintousers(name)values(?)

2014-01-0910:24:57,537infosqlalchemy.engine.base.engine(('ghost',),('test',))

2014-01-0910:24:57,537infosqlalchemy.engine.base.enginecommit

<sqlalchemy.engine.result.resultproxyobjectat0x31bcd50>

>>>

数据库内容为

代码如下:

sqlite>select*fromusers;

1|rsj217|rsj21@gmail.com

2|ghost|

3|test|

sqlite>

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

三使用orm

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

创建映射

代码如下:

>>>classuser(object):

...def__repr__(self):

...return'%s(%r,%r)'%(self.__class__.__name__,self.name,self.email)

...

>>>mapper(user,users_table)#创建映射

<mapperat0x31bcfd0;user>

>>>ul=user()

>>>ul.name

>>>printul

user(none,none)

>>>printul.name

none

>>>

建立会话

查询

代码如下:

>>>session=create_session()

>>>session

<sqlalchemy.orm.session.sessionobjectat0x31bef10>

>>>query=session.query(user)

>>>query

<sqlalchemy.orm.query.queryobjectat0x31bee50>

>>>u=query.filter_by(name='rsj217').first()

2014-01-0910:44:23,809infosqlalchemy.engine.base.engineselectusers.idasusers_id,users.nameasusers_name,users.emailasusers_email

fromusers

whereusers.name=?

limit?offset?

2014-01-0910:44:23,809infosqlalchemy.engine.base.engine('rsj217',1,0)

>>>u.name

u'rsj217'

>>>

插入

代码如下:

>>>fromsqlalchemyimport*

>>>fromsqlalchemy.ormimport*

>>>engine=create_engine('sqlite:///./sqlalchemy.db')

>>>metadata=metadata(engine)

>>>users_table=table('users',metadata,autoload=true)

>>>classuser(object):pass

...

>>>mapper(user,users_table)

<mapperat0x18185d0;user>

>>>session=sessionmaker(bind=engine)

>>>session=session()

>>>u=user()

>>>u.name='new'

>>>session.add(u)

>>>session.flush()

>>>session.commit()

>>>

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

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

2025公考·省考培训课程试听预约报名

  • 报班类型
  • 姓名
  • 手机号
  • 验证码
推荐信息
Baidu
map