python orm模块sqlalchemy的简单使用(增删改查)

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()

你可能感兴趣的:(python,sqlalchemy)