1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 #python 5 #2017/7/6 21:29 6 #__author__='Administrator' 7 from sqlalchemy.ext.declar ...
1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 #python 5 #2017/7/6 21:29 6 #__author__='Administrator' 7 from sqlalchemy.ext.declarative import declarative_base 8 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index 9 from sqlalchemy.orm import sessionmaker, relationship 10 from sqlalchemy import create_engine 11 from sqlalchemy import func #統計 12 13 # 用戶 密碼 主機 庫 14 engine = create_engine("mysql+pymysql://root:[email protected]:3306/test",encoding="utf-8",echo=False) 15 16 Base = declarative_base()#生成orm 基類 17 class User_2(Base): 18 __tablename__='user' #表名 19 id = Column(Integer,primary_key=True)#整數類型 設為主鍵 20 name = Column(String(32))#字元串類型 21 age = Column(Integer) 22 addr= Column(String(256)) 23 24 def __repr__(self):#輸出查詢 25 return '%s>name:%s--age:%saddrs:%s'%(self.id,self.name,self.age,self.addr) 26 27 28 Session_class=sessionmaker(bind=engine)#創建與資料庫的會話 類 29 Session=Session_class()#生成實例 30 31 #增加 32 ''' 33 user_obj =User(name="sa2",addrs="1234")#生成你要創建的數據對象 34 Session.add(user_obj)# 添加記錄 35 ''' 36 #添加一組數據 37 ''' 38 Session.add_all([ 39 User(name="abcg",age=34,addr="sdfsdf"), 40 User(name="bcdq",age=11,addr="chaense") 41 ]) 42 ''' 43 #刪除 44 ''' 45 Session.query(User).filter(User.id>3).filter(User.id<6).delete() 46 ''' 47 # 查詢 條件 所有 48 data =Session.query(User_2).filter_by(id=2).all() 49 # 多個條件 50 data2 =Session.query(User_2).filter(User_2.id>2).filter(User_2.id<5).all() 51 52 53 #改 54 55 Session.query(User_2).filter(User_2.id ==2).update({"name" : "099"}) 56 print(data) 57 print(data2) 58 ''' 59 print(Session.query(User).filter(User.id>2).filter(User.name.in_(["sa",'sa2'])).all()) 60 Session.rollback()#回滾操作 61 print(Session.query(User).filter(User.id>2).filter(User.name.in_(["sa",'sa2'])).all()) 62 ''' 63 print(Session.query(User_2).filter(User_2.id>2).filter(User_2.name.in_(["sa",'sa2'])).count())#統計符合條件出現的次數 64 counts=Session.query(User_2).filter(User_2.id>2).filter(User_2.name.in_(['bcd'])).count()#統計符合條件出現的次數 65 print(counts) 66 #分組查詢 欄位 統計次數 欄位 67 gurps=Session.query(User_2.name,func.count(User_2.name)).group_by(User_2.name).all() 68 print(gurps) 69 # 以addrs為條件 70 gurps1=Session.query(User_2.name,func.count(User_2.name)).group_by(User_2.addr).all() 71 print(gurps1) 72 73 74 Session.commit()#關閉事務View Code
sqlalchemy 基本操作
1 from sqlalchemy.ext.declarative import declarative_base 2 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index 3 from sqlalchemy.orm import sessionmaker, relationship 4 from sqlalchemy import create_engine 5 # 用戶 密碼 主機 庫 6 engine = create_engine("mysql+pymysql://root:[email protected]:3306/test",encoding="utf-8",echo=True) 7 8 Base = declarative_base()#生成orm 基類 9 class User(Base): 10 __tablename__='info_l' #表名 11 id = Column(Integer,primary_key=True)#整數類型 設為主鍵 12 name = Column(String(32))#字元串類型 13 addrs= Column(String(256)) 14 15 Base.metadata.create_all(engine)#創建表結構 16 17 Session_class=sessionmaker(bind=engine)#創建與資料庫的會話 類 18 Session=Session_class()#生成實例 19 20 user_obj =User(name="sa",addrs="1234")#生成你要創建的數據對象 21 print(user_obj.name,user_obj.addrs)#此時並未創建對象 22 Session.add(user_obj)#開啟事務進行連接 添加記錄 23 Session.commit()#關閉事務View Code
外鍵操作示例
1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 #python 5 #2017/7/7 10:28 6 #__author__='Administrator' 7 import sqlalchemy 8 from sqlalchemy.ext.declarative import declarative_base 9 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index,DATE 10 from sqlalchemy.orm import sessionmaker, relationship 11 from sqlalchemy import create_engine 12 # 用戶 密碼 主機 庫 13 engine = create_engine("mysql+pymysql://root:[email protected]:3306/test",encoding="utf-8",echo=False) 14 15 Base = declarative_base()#生成orm 基類 16 17 class Studes(Base):#學生類 18 __tablename__ ='studes' 19 id = Column(Integer,primary_key=True)#整數類型 設為主鍵 20 name = Column(String(32),nullable=False)#字元串類型 不能為空 21 register_day= Column(DATE,nullable=False)#日期 22 23 def __repr__(self):#輸出查詢 24 return '%s>name:%s--register_day :%s'%(self.id,self.name,self.register_day) 25 26 27 class Studes_Cr(Base):#課程類 28 __tablename__ ='stud_cr' 29 id = Column(Integer,primary_key=True)#整數類型 設為主鍵 30 day= Column(Integer,nullable=False) 31 status= Column(String(35),nullable=False)#上課記錄 32 stu_id= Column(Integer,ForeignKey("studes.id",))#外鍵關聯 33 studes=relationship("Studes",backref="m_study_reg")#自定義關聯反查 34 35 def __repr__(self):#輸出查詢 自定義 外鍵關聯調用 36 return '%s>day:%s status:%s'%(self.studes.name,self.day,self.status) 37 38 Base.metadata.create_all(engine)#創建表結構 39 40 Session_class=sessionmaker(bind=engine)#創建與資料庫的會話 類 41 Session=Session_class()#生成實例 42 43 ''' 44 s1 = Studes(name="Alex",register_day='2017-05-06')#學生 45 s2 = Studes(name="bolg",register_day='2017-03-06') 46 s3 = Studes(name="calm",register_day='2017-01-07') 47 s4 = Studes(name="Defr",register_day='2017-03-16') 48 s5 = Studes(name="Eale",register_day='2017-02-24') 49 50 study_obj1=Studes_Cr(day=1,status="YES",stu_id=1)#上課記錄 51 study_obj2=Studes_Cr(day=1,status="YES",stu_id=2)#上課記錄 52 study_obj3=Studes_Cr(day=1,status="NO",stu_id=3)#上課記錄 53 study_obj4=Studes_Cr(day=1,status="YES",stu_id=4)#上課記錄 54 study_obj5=Studes_Cr(day=2,status="NO",stu_id=1)#上課記錄 55 study_obj6=Studes_Cr(day=2,status="YES",stu_id=2)#上課記錄 56 study_obj7=Studes_Cr(day=2,status="YES",stu_id=3)#上課記錄 57 58 #一次全部添加 59 Session.add_all([s1,s2,s3,s4,s5,study_obj1,study_obj2,study_obj3,study_obj4,study_obj5,study_obj6,study_obj7]) 60 ''' 61 62 63 #查詢 學生對應的信息 64 stu_obj= Session.query(Studes).filter(Studes.name=="Alex").first() 65 print(stu_obj) 66 #通過外鍵進行相關信息查詢 67 print(stu_obj.m_study_reg) 68 69 Session.commit()View Code
外鍵 多外鍵關聯示例: 多外鍵關聯.py 多外鍵_操作.py
多外鍵關聯.py
1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 #python 5 #2017/7/7 13:06 6 #__author__='Administrator' 7 8 from sqlalchemy import Integer, ForeignKey, String, Column 9 from sqlalchemy.ext.declarative import declarative_base 10 from sqlalchemy.orm import relationship 11 from sqlalchemy import create_engine 12 13 Base = declarative_base()#生成orm 基類 14 class Customer(Base): 15 __tablename__ = 'customer' 16 id = Column(Integer, primary_key=True) 17 name = Column(String(32),nullable=False) 18 19 billing_address_id = Column(Integer, ForeignKey("address.id"))#帳單地址外鍵關聯 20 shipping_address_id = Column(Integer, ForeignKey("address.id"))#收貨地址外鍵關聯 21 22 billing_address = relationship("Address",foreign_keys=[billing_address_id])#帳單地址自定義反查 對應外鍵 23 shipping_address = relationship("Address",foreign_keys=[shipping_address_id])#收貨地址 24 25 class Address(Base): 26 __tablename__ = 'address' 27 id = Column(Integer, primary_key=True) 28 street = Column(String(32))#詳細 29 city = Column(String(32))#市 30 state = Column(String(255))#省 31 32 def __repr__(self): 33 return self.state+self.city+self.street 34 35 # 用戶 密碼 主機 庫 36 engine = create_engine("mysql+pymysql://root:[email protected]:3306/test",encoding="utf-8",echo=False) 37 38 39 Base.metadata.create_all(engine)#創建表結構View Code
多外鍵_操作.py
1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 #python 5 #2017/7/7 13:21 6 #__author__='Administrator' 7 import os ,sys 8 from day66 import 多外鍵關聯 9 from sqlalchemy.orm import relationship,sessionmaker 10 from sqlalchemy import create_engine 11 Session_class=sessionmaker(bind=多外鍵關聯.engine)#創建與資料庫的會話 類 12 Session=Session_class()#生成實例 13 ''' 14 addr1=多外鍵關聯.Address(street="btxw",city='xy',state="fj") 15 addr2=多外鍵關聯.Address(street="jjqy",city='qz',state="fj") 16 addr3=多外鍵關聯.Address(street="ml",city='pt',state="fj") 17 18 Session.add_all([addr1,addr2,addr3])#寫入資料庫 19 20 c1=多外鍵關聯.Customer(name='calmyan',billing_address=addr1,shipping_address=addr1) 21 c2=多外鍵關聯.Customer(name='alex',billing_address=addr3,shipping_address=addr2) 22 Session.add_all([c1,c2]) 23 ''' 24 25 #查詢 26 sobj=Session.query(多外鍵關聯.Customer).filter(多外鍵關聯.Customer.name=='calmyan').first() 27 28 print(sobj.name,sobj.billing_address,sobj.shipping_address) 29 30 Session.commit()View Code
多對多外鍵示例:
orm_s.py
1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 #python 5 #2017/7/7 14:07 6 #__author__='Administrator' 7 8 #一本書可以有多個作者,一個作者又可以出版多本書 9 10 11 from sqlalchemy import Table, Column, Integer,String,DATE, ForeignKey 12 from sqlalchemy.orm import relationship 13 from sqlalchemy.ext.declarative import declarative_base 14 from sqlalchemy import create_engine 15 from sqlalchemy.orm import sessionmaker 16 17 Base = declarative_base() 18 19 #創建第三張表,自動維護 20 book_m2m_author = Table('book_m2m_author', Base.metadata, 21 Column('book_id',Integer,ForeignKey('books.id')),#關聯外鍵,書id 22 Column('author_id',Integer,ForeignKey('authors.id')),#關聯外鍵,作者id 23 ) 24 25 class Book(Base):#書名 26 __tablename__ = 'books' 27 id = Column(Integer,primary_key=True) 28 name = Column(String(64)) 29 pub_date = Column(DATE) 30 authors = relationship('Author',secondary=book_m2m_author,backref='books') 31 32 def __repr__(self): 33 return self.name 34 35 class Author(Base):#作者 36 __tablename__ = 'authors' 37 id = Column(Integer, primary_key=True) 38 name = Column(String(32)) 39 40 def __repr__(self): 41 return self.name 42 43 # 用戶 密碼 主機 庫 44 engine = create_engine("mysql+pymysql://root:[email protected]:3306/test?charset=utf8",encoding="utf-8",echo=False) 45 46 47 Base.metadata.create_all(engine)#創建表結構View Code
orm_s_aut.py
1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 #python 5 #2017/7/7 14:38 6 #__author__='Administrator' 7 8 from day66 import orm_s 9 from sqlalchemy.orm import relationship,sessionmaker 10 Session_class = sessionmaker(bind=orm_s.engine) #創建與資料庫的會話session class ,註意,這裡返回給session的是個class,不是實例 11 s = Session_class() #生成session實例 12 ''' 13 #book名 14 b1 = orm_s.Book(name="跟Alex學Python") 15 b2 = orm_s.Book(name="跟Alex學把妹") 16 b3 = orm_s.Book(name="跟Alex學裝逼") 17 b4 = orm_s.Book(name="跟Alex學開車") 18 19 #作者名 20 a1 = orm_s.Author(name="Alex") 21 a2 = orm_s.Author(name="Jack") 22 a3 = orm_s.Author(name="Rain") 23 24 #關聯關係 25 b1.authors = [a1,a2] 26 b2.authors = [a1,a2,a3] 27 28 s.add_all([b1,b2,b3,b4,a1,a2,a3]) 29 ''' 30 31 32 ''' 33 #查詢 作者表 條件 作者名==alex 34 aut_obj=s.query(orm_s.Author).filter(orm_s.Author.name=='Alex').first()#返回一個對象 35 print(aut_obj,aut_obj.books,aut_obj.books[0]) 36 ''' 37 38 #更新 39 s.query(orm_s.Book).filter(orm_s.Book.id ==2).update({"pub_date" : "2017-06-07"}) 40 41 #查詢 書表 條件 書id==2 42 book_obj=s.query(orm_s.Book).filter(orm_s.Book.id==2).first() 43 book_obj2=s.query(orm_s.Book).filter(orm_s.Book.id==1).first() 44 print(book_obj.authors,book_obj)#輸出書的作者 書名 45 #book_obj.authors.remove(aut_obj)#刪除書中的一個作者 46 print(book_obj2.authors,book_obj2)#輸出書的作者 書名 47 48 #刪除作者,會把這個作者跟所有書的關聯關係數據也自動刪除 49 ''' 50 s.delete(aut_obj) 51 ''' 52 book_obj=s.query(orm_s.Book).filter(orm_s.Book.id==2).first() 53 book_obj2=s.query(orm_s.Book).filter(orm_s.Book.id==1).first() 54 print(book_obj.authors,book_obj)#輸出書的作者 書名 55 print(book_obj2.authors,book_obj2)#輸出書的作者 書名 56 57 58 s.commit()View Code