标签:相关 utf-8 删除 uri 清空 ring ade main odi
#encoding: utf-8 from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Text, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker,relationship,backref from random import randint HOSTNAME = ‘127.0.0.1‘ PORT = 3306 DATABASE = ‘first_sqlalchemy‘ USERNAME = ‘root‘ PASSWORD = ‘123456‘ #dialect+driver://username:password@host:port/database DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) # Session = sessionmaker(engine) # session = Session() session = sessionmaker(engine)() #Session(**local_kw) class User(Base): __tablename__ = ‘user‘ id = Column(Integer,primary_key=True,autoincrement=True) username = Column(String(50),nullable=False,unique=True) class Article(Base): __tablename__ = ‘article‘ id = Column(Integer,primary_key=True,autoincrement=True) article_name = Column(String(50),nullable=False) uid = Column(Integer,ForeignKey(‘user.id‘)) author = relationship(‘User‘,backref=‘articles‘,cascade=‘save-update,delete‘)#其实这里还有默认字段cascade #cascade的属性,只能当前字段上,这里还有另一种写法,两个关联字段都设置 # author = relationship(‘User‘, backref=backref(‘articles‘,cascade=‘save-update,delete‘), cascade=‘save-update,delete‘) # cascade=save-update:默认选项,在添加一条数据的时候,会把其它和它相关联的数据都添加到数据中, #这就是 cascade = save-update的作用。 #merge:默认选项。当使用session.merge,合并一个对象的时候,会将使用了relationship相关联的对象也进行merge操作。 #expunge:移除操作的时候,会将相关联的对象也进行移除。这个操作只是从session中移除,并不会真正的从数据库中删除。 #增加数据 def init_db(): #清空数据库,除多对多关系外 Base.metadata.drop_all() #把数据映射到数据中 Base.metadata.create_all() user = User(username=‘辰东‘) article = Article(article_name=‘遮天‘) article1 = Article(article_name=‘圣墟‘) article.author = user article1.author = user session.add_all([article, article1]) session.commit() #cascade = delete ,relationship关联的数据删除,只要有关联的数据都删除 def operation(): #获取article的对象,这个对象关联(article.author=user)也就是user=session.query(User).first()的对象 article = session.query(Article).first() session.delete(article)#这里删除article对象,由于cascde=delete这个属性,relationship关联的user对象也会随之删除 # session.merge(article)相当字典的update操作,有就替换掉,没有就合拼 #session.expunge(article)只会将对象从session中删除,不会从数据库中删除, #区别session.delete(article) session.commit() if __name__ == ‘__main__‘: # init_db() operation()
标签:相关 utf-8 删除 uri 清空 ring ade main odi
原文地址:https://www.cnblogs.com/wuheng-123/p/9710829.html