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
Type"help","copyright","credits"or"license"formoreinformation.
>>>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".help"forinstructions
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',
2014-01-0910:24:02,250INFOsqlalchemy.engine.base.EngineINSERTINTOusers(name,email)VALUES(?,?)
2014-01-0910:24:02,250INFOsqlalchemy.engine.base.Engine('rsj217',
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;
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的方式更好
剩下删除关系事物等高级操作就参考官方文档了。
更多信息请查看IT技术专栏