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()
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。