当前位置:Gxlcms > Python > python第六十六天--sqlalchemy

python第六十六天--sqlalchemy

时间:2021-07-01 10:21:17 帮助过:23人阅读

 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:root@127.0.0.1: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:root@127.0.0.1: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:root@127.0.0.1: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:root@127.0.0.1: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:root@127.0.0.1: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

 

 

 

以上就是python第六十六天--sqlalchemy的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行