sqlalchemy简单示例
1、初始化数据库database.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by miaoshuijian on 2017/3/13 from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import scoped_session, sessionmaker # print MOIRAI_DB_CONNECT_STRING engine = create_engine('mysql+pymysql://root:@127.0.0.1:3306/secdev?charset=utf8') metadata = MetaData() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) def init_db(): metadata.create_all(bind=engine) def shutdown_session(exception=None): db_session.remove()
2、
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by miaoshuijian on 2017/3/13 from sqlalchemy import Table, Column, Integer, String from sqlalchemy.orm import mapper from database import metadata, db_session class User(object): query = db_session.query_property() def __init__(self, name=None, email=None): self.name = name self.email = email def __repr__(self): return '<User %r>' % (self.name) users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(50), unique=False), Column('email', String(120), unique=False) ) mapper(User, users)
3、操作:
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by miaoshuijian on 2017/3/13 from database import init_db, db_session, shutdown_session from models import User if __name__=='__main__': init_db() u = User('admin', 'admin@localhost') db_session.add(u) db_session.commit() print User.query.all() print User.query.filter(User.name == 'admin').first() shutdown_session()