Python 之 sqlalchemy删

2023-01-31 02:01:30 python sqlalchemy

表结构:

Python 之 sqlalchemy删除数据

Python 之 sqlalchemy删除数据

代码:

#Author Kang

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
from sqlalchemy.ORM import sessionmaker

#创建对象的基类:
Base = declarative_base()

#定义User对象:
class User(Base):
    #表的名字:
    __tablename__ = 'user'

    #表的结构:
    userid = Column(Integer,primary_key=True)
    username = Column(String(20))
    age = Column(Integer)
    department = Column(String(20))

#初始化数据库连接
engine = create_engine("Mysql+pymysql://kang:123456@10.3.152.35/test",encoding="utf-8")

#创建session类型
DBSession = sessionmaker(bind=engine)

#创建session对象
session = DBSession()

#先查询,后删除
session.query(User).filter(User.username == "Jack").delete()
session.commit()
session.close()

相关文章