• SQLAlchemy MySQL 基础


    __author__ = 'Steve'
    
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, String
    
    Base = declarative_base()
    
    
    # define the schema of table
    class Users2(Base):
        __tablename__ = 'users2'
        name = Column(String(45), nullable=True)
        id = Column(Integer, primary_key=True)
    
    
    # you can direct query database, but it is not recommended
    def test_conn():
        username = 'root'
        passwd = '123'
        schema = 'test'
        engine = create_engine(
            "mysql://{0}:{1}@127.0.0.1/{2}?charset=utf8&use_unicode=0".format(username, passwd, schema))
        result = engine.execute("select name from users2")
        for row in result:
            print "name:", row['name']
        result.close()
    
    
    def conn():
        username = 'root'
        passwd = '123'
        schema = 'test'
        engine = create_engine(
            "mysql+mysqldb://{0}:{1}@127.0.0.1/{2}?charset=utf8&use_unicode=0".format(username, passwd, schema))
        Base.metadata.bind = engine
        DBSession = sessionmaker(bind=engine)
        session = DBSession()
        return session
    
    
    def query():
        session = conn()
        rows = session.query(Users2).all()
        for row in rows:
            print row.id, row.name
    
    
    def insert():
        user = Users2(name="steve", id=3)
        session = conn()
        session.add(user)
        session.commit()
    
    
    def delete():
        session = conn()
        user = session.query(Users2).filter_by(name='steve2').one()
        print "delete user:", user.name
        session.delete(user)
        session.commit()
    
    
    def update():
        session = conn()
        user = session.query(Users2).filter_by(name='steve').one()
        user.name = 'steve2'
        session.commit()
    
    
    if __name__ == "__main__":
        query()
        print
        # insert()
        # delete()
        # update()
        query()
  • 相关阅读:
    VUE 引入element ui 样式不生效解决
    Spark项目故障思路整理总结
    Spark-环境安装
    01.Kettle的安装-千亿级数仓环境搭建
    千亿级数仓day01-项目的简介
    Umeng项目day04
    Umengday12-统计指标
    Umengday11-azkaban调度
    Umengday09-hive自定义UDTF函数叉分函数
    Docker配置jdk1.8
  • 原文地址:https://www.cnblogs.com/phoenix13suns/p/4516227.html
Copyright © 2020-2023  润新知