sqlalchemy 简单实例

本文地址:http://blog.csdn.net/spch2008/article/details/9014559


from sqlalchemy import *
from sqlalchemy.orm import sessionmaker, mapper
from obj.dbobj import User


def init_db():
    engine = create_engine("mysql://root:sqlPwd@localhost/chat")
    metadata = MetaData()

    table = Table('users', metadata,
                    Column('user_id', String(20), primary_key=True),
                    Column('user_pwd', String(20))
                 )
    metadata.create_all(engine)

    mapper(User, table)
    
    Session = sessionmaker(engine)
    return Session()


class database:
    def __init__(self, session):
        self.session = session
        self.query   = self.session.query(User)
    
    def getUser(self, user_id):
        return self.query.get(user_id)
 
    def getPwd(self, user_id):
        user = self.getUser(user_id)
        return user.pwd()
        
    
    def insertInfo(self, user_id, pwd):
        user = User(user_id, pwd)
        self.session.add(user)
        self.session.commit()
    
    def deleteInfo(self, user_id):
        user = self.getUser(user_id)
        self.session.delete(user)
        self.session.commit()
    
    def getCount(self):
        return self.query.count()
    
    def getAllUser(self):
        return self.query.all()
    
    def modifyPwd(self, user_id, pwd):
        self.query.filter(User.user_id == user_id).update({"user_pwd" : pwd})
        self.session.commit()



def getDB():
    engine = init_db()
    db = database(engine)
    return db


你可能感兴趣的:(sqlalchemy 简单实例)