python中orm 框架有哪些

发布网友 发布时间:2022-03-03 12:28

我来回答

1个回答

热心网友 时间:2022-03-03 13:57

对多核多对多

1234567101112131415161718192021222324252627282930313233343536373839404142434445

from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Indexfrom sqlalchemy.orm import sessionmaker,relationshipfrom sqlalchemy import create_engineengine = create_engine("mysql+pymysql://root:123456@192.168.180.129:3306/test",max_overflow=5)Base = declarative_base()#创建单表class Users(Base): __tablename__ = 'users' id = Column(Integer,primary_key=True) name = Column(String(32)) extra = Column(String(16)) #一对多 class Favor(Base): __tablename__ = 'favor' nid = Column(Integer,primary_key=True) caption = Column(String(50),default='red',unique=True) class Person(Base): __tablename__ = 'person' nid = Column(Integer,primary_key=True) name = Column(String(32),index=True,nullable=True) favor_id = Column(Integer,ForeignKey('favor.nid')) #多对多class Group(Base): __tablename__ = 'group' nid = Column(Integer,primary_key=True) name = Column(String(),unique=True,nullable=False) port = Column(Integer,default=22) class Server(Base): __tablename__ = 'server' id = Column(Integer,primary_key=True,autoincrement=True) hostname = Column(String(),unique=True,nullable=False)class ServerToGroup(Base): __tablename__ = 'servertogroup' nid = Column(Integer,primary_key=True,autoincrement=True) server_id = Column(Integer, ForeignKey('server.id')) group_id = Column(Integer, ForeignKey('group.nid'))# Base.metadata.create_all(engine) #生成表Base.metadata.drop_all(engine) #生成表

#添加数据(往Users表增加数据)

1234567101112131415

from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Indexfrom sqlalchemy.orm import sessionmaker,relationshipfrom sqlalchemy import create_enginefrom orm一对多和多对多 import Users #从orm一对多和对多程序中导入Users类engine = create_engine("mysql+pymysql://root:123456@192.168.180.129:3306/test",max_overflow=5)Base = declarative_base()Base.metadata.create_all(engine) #生成表# Base.metadata.drop_all(engine) #生成表Session = sessionmaker(bind=engine)session = Session()#增加数据obj = Users(name="parktrick",extra="Devops")session.add(obj)session.commit() #不执行这步,数据是写入不了数据库的

#删除User表某条数据

123

#删除数据session.query(Users).filter(Users.id > 2).delete() #把Users.id大于2的数据删除掉session.commit()

#修改数据

123
#修改数据session.query(Users).filter(Users.id > 1).update({"name":"bob"}) #修改User.id大于1的name为"bob"session.commit()

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com