python ormモジュールsqlalchemyの簡単な使用(削除変更)

1704 ワード

from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.mysql import TEXT, INTEGER, VARCHAR, DATETIME, TINYINT

#        
Base = declarative_base()


#   User  
class User(Base):
    #     
    __tablename__ = 'user'

    #     
    id = Column(INTEGER, primary_key=True, autoincrement=True, comment='id     id')
    name = Column(String(20))


#         
engine = create_engine('mysql+pymysql://root:xiaoge@localhost:3306/tapp')

#   DBSession  
DBSession = sessionmaker(bind=engine)

# #   
# #   Session  
# session = DBSession()
# #   User  
# new_user = User(name='Bob')
# #    session
# session.add(new_user)
# #   
# session.commit()
# #   session
# session.close()

#   
#   session
session = DBSession()
#   session    ,query(   ).filter(  ).one()/all()
# filters = {'name': 'Bob', 'id': 6}
# user_list = session.query(User).filter_by(**filters).filter(User.id > 1).all()
# filters = {'name': , 'id': 6}
user_list = session.query(User).filter(User.name.like('Bob'), User.id.like(2)).all()
for user in user_list:
    print('type:{0}'.format(user.id))
    print('name:{0}'.format(user.name))
#   session
session.close()

# #   
# session = DBSession()
# user_result = session.query(User).filter_by(id='5').first()
# user_result.name = "jack"
# session.commit()
# session.close()

#   
# session = DBSession()
# user_del = session.query(User).filter_by(id='5').first()
# session.delete(user_del)
# session.commit()
# session.close()