Python SqlAlchemy使用方法

Python SqlAlchemy使用方法

1.初始化连接

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql://pass@localhost/test'echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()
ret=session.execute('desc user')
print ret
# print ret.fetchall()print ret.first()

mysql://root:pass/test
root是用户名 pass密码 test数据库
session相当于MySQLdb里面的游标
first 相当于fetchone
echo=True 会输出所有的sql

2.创建表

from sqlalchemy import Column
from sqlalchemy.types import *
from sqlalchemy.ext.declarative import declarative_base

BaseModel = declarative_base()

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql://root:Hs2BitqLYKoruZJbT8SV@localhost/test')
DBSession = sessionmaker(bind=engine)


class User(BaseModel):
    __tablename__ = 'user1'  # 表名
    user_name = Column(CHAR(30), primary_key=True)
    pwd = Column(VARCHAR(20), default='aaa', nullable=False)
    age = Column(SMALLINT(), server_default='12')
    accout = Column(INT())
    birthday = Column(TIMESTAMP())
    article = Column(TEXT())
    height = Column(FLOAT())


def init_db():'''
    初始化数据库
    :return:
    '''
    BaseModel.metadata.create_all(engine)


def drop_db():'''
    删除所有数据表
    :return:
    '''
    BaseModel.metadata.drop_all(engine)


drop_db()
init_db()

和django的 ORM一样 一旦表被创建了,修改User类不能改变数据库结构,只能用sql语句或删除表再创建来修改数据库结构
sqlalchemy.types里面有所有的数据字段类型,等于sql类型的大写
default参数是插入数据的时候,sqlalchemy自己处理的,server_default才是让mysql处理的

3.添加记录

user1=User(user_name='lujianxing',accout=1245678)
session.add(user1)
session.commit()

要commit才能起作用

4.更新记录

1.更新单条记录

query = session.query(User) 
user = query.get('lujianxing11')
print user.accout
user.accout='987'
session.flush()

2.更新多条记录

query = session.query(User)
query.filter(User.user_name=='lujianxing2').update({User.age: '15'})
query.filter(User.user_name=='lujianxing2').update({'age': '16'})
query.filter(User.pwd=='aaa').update({'age': '17'})

5.删除记录

query = session.query(User)
user = query.get('lujianxing11')
session.delete(user)
session.flush()

6.查询

query = session.query(User)
print query  # 只显示sql语句,不会执行查询print query[0]  # 执行查询print query.all()  # 执行查询print query.first()  # 执行查询for user in query:  # 执行查询print user.user_name

如果字段的类型是数字型,查询出来的type也是数字型的,不是字符串
高级一点的查询:

# 筛选
user = query.get(1) # 根据主键获取print query.filter(User.user_name == 2)  # 只显示sql语句,不会执行查询print query.filter(User.user_name == 'lujianxing').all()  # 执行查询print query.filter(User.user_name == 'lujianxing', User.accout == 1245678, User.age > 10).all()  # 执行查询print query.filter(User.user_name == 'lujianxing').filter(User.accout == 1245678).all()
print query.filter("user_name = 'lujianxing'").all()  # 执行查询print query.filter("user_name = 'lujianxing' and accout=1245678").all()  # 执行查询
query2 = session.query(User.user_name)  # 返回的结果不是User的实例,而是元组print query2.all()  # 执行查询print query2.offset(1).limit(1).all()  # 等于 limit 1,1# 排序print query2.order_by(User.user_name).all()  
print query2.order_by('user_name').all()  
print query2.order_by(User.user_name.desc()).all()
print query2.order_by(User.user_name, User.accout.desc()).all()
print query2.filter("user_name = 'lujianxing' and accout=1245678").count()
# 聚合查询print session.query(func.count('*')).select_from(User).scalar()
print session.query(func.count('1')).select_from(User).scalar()
print session.query(func.count(User.id)).scalar()
print session.query(func.count('*')).filter(User.id > 0).scalar() # filter() 中包含 User,因此不需要指定表print session.query(func.count('*')).filter(User.name == 'a').limit(1).scalar() == 1 # 可以用 limit() 限制 count() 的返回数print session.query(func.sum(User.id)).scalar()
print session.query(func.now()).scalar() # func 后可以跟任意函数名,只要该数据库支持print session.query(func.current_timestamp()).scalar()
print session.query(func.md5(User.name)).filter(User.id == 1).scalar()

参考文章
英文文档
Engine Configuration
中文
Python SQLAlchemy基本操作和常用技巧




http://www.jianshu.com/p/152685de2533

SQLAlchemy 教程


SQLAlchemy 是python 操作数据库的一个库。能够进行 orm 映射官方文档 sqlchemy
SQLAlchemy“采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型”。SQLAlchemy的理念是,SQL数据库的量级和性能重要于对象集合;而对象集合的抽象又重要于表和行。
一 安装 SQLAlchemy

pip install sqlalchemy

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

>>> import sqlalchemy
>>> sqlalchemy.__version__'0.9.1'>>>

二 使用 sqlalchemy对数据库操作
(1). 定义元信息,绑定到引擎

>>> 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:22Enter ".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 的方式更好
剩下删除 关系 事物等高级操作就参考官方文档了.









posted @ 2016-07-30 09:12  Ju-do-it  阅读(23493)  评论(1编辑  收藏  举报