__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()
时间: 2024-12-28 23:56:40