Flask中的的SQLAlchemy

很久沒有更新Blog了mysql

今天來聊一聊 Python 的 ORM 框架 SQLAlchemy 有的孩子已經據說過這個框架的大名了,也據說了 SQLAlchemy 沒有 Django 的 Models 好用sql

我在這裏闢謠一下, Models 牢牢只是配置和使用比較簡單,由於他是Django自帶的ORM框架,也正是由於是Django原生的,因此兼容性遠遠不如SQLAlchemy數據庫

真正算得上全面的ORM框架是咱們的SQLAlchemy ORM框架,它能夠在任何使用SQL查詢時使用session

固然了,不管是使用什麼ORM框架,都是爲了方便不熟練數據庫的同窗使用的,我的仍是比較推崇原生 SQL 哈框架

ok,咱們來看一下 SQLAlchemy 如何使用:ide

1.建立表的一波說不出來但很牛x的操做編碼

#create_table.py 
#經過SQLAlchemy建立數據表
# 1.導入SQLAlchemy,沒安裝的記得安裝一下啊 from sqlalchemy.ext.declarative import declarative_base # 2.建立ORM模型基類 Base = declarative_base() # 至關於Django Model # 3.導入ORM對應數據庫數據類型的字段 from sqlalchemy import Column, Integer, String # 4.建立ORM對象 class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(32), index=True) # 5.建立數據庫鏈接 from sqlalchemy import create_engine #mysql+pymysql用mysql數據庫+pymysql,root用戶,614615數據庫密碼,@127.0.0.1本地地址,3306數據庫端口號,led數據庫名,剩下的是字符編碼,這要是不懂,滾!!! engine = create_engine("mysql+pymysql://root:614615@127.0.0.1:3306/led?charset=utf8") # 數據庫鏈接建立完成 # 6.去數據庫中建立與User所對應的數據表 # 去engine數據庫中建立全部繼承Base類的 ORM對象 Base.metadata.create_all(engine)

2.增的操做spa

#curd_insert.py

#
# 1.打開數據庫的連接
from create_table import engine
# 2.建立繪畫
from sqlalchemy.orm import sessionmaker
# 3.建立會話的窗口
Session = sessionmaker(engine)
# 4.打開會話窗口
db_session = Session()
from create_table import User
with open('name.txt','r')as f:
    for i in f.read():
        db_session.add_all([
            User(name=i),
        ])

        db_session.commit()
        db_session.close()
#這裏說一下,add和add_all的區別,就是單挑和多條的差距,固然,add_all也能夠插入單條,只不過消耗的資源多一些,
View Code

 

3.5改的高級操做3d

#curd_update_more.py

from sqlalchemy.orm import sessionmaker
from create_table import User,engine
Session = sessionmaker(engine)
db_session = Session()

#直接修改
db_session.query(User).filter(User.id > 10).update({"name":"001"})
db_session.commit()
db_session.close()


#原有值的基礎上添加 -2
db_session.query(User).filter(User.id > 0).update({User.name:User.name + "-2"},synchronize_session=False)
db_session.commit()
db_session.close()
View Code

 

3.改的操做code

#curd_update.py


# 更新

from sqlalchemy.orm import sessionmaker
from create_table import User,engine
Session = sessionmaker(engine)
db_session = Session()

ret = db_session.query(User).filter(User.name == "李志強").update({"name":"好人"})
db_session.commit()#切記!!執行語句
db_session.close()#關閉會話




ret = db_session.query(User).filter(User.id >=60).update({"name":"我是好人"})
db_session.commit()
db_session.close()
View Code

4.查的操做

#curd_select.py

#

from create_table import engine
from create_table import User
from sqlalchemy.orm import sessionmaker

Session = sessionmaker(engine)
db_session = Session()

# 1.簡單的查詢
res = db_session.query(User).all()
for i in res:
    print(i.name)

res_list = db_session.query(User).first()
print(res_list.id)


# 2.有條件的查詢
ret = db_session.query(User).filter(User.name == "李二短").first()
# 由於這裏查到一個因此不會用索引取值
print(ret.name,ret.id)

ret = db_session.query(User).filter(User.name == "").all()
# 這裏查到全部因此會用索引取值第一個
print(ret[0].name,ret[0].id)

ret = db_session.query(User).filter(User.id >= 60).all()
# 這裏說一下,查詢全部的id>=60的,查詢全部進行遍歷取值
for i in ret:
    print(i.name,i.id)


# 查看原生的sql語句辦法
ret = db_session.query(User).filter(User.id >= 60)
print(ret)
View Code

5.刪除的操做

curd_delete.py
# 刪除

from sqlalchemy.orm import sessionmaker
from create_table import engine,User

Session = sessionmaker(engine)
db_session = Session()

ret = db_session.query(User).filter(User.name == "我是好人").delete()
db_session.commit()
db_session.close()
# print(ret)


ret = db_session.query(User).filter(User.id >= 20).delete()
db_session.commit()
db_session.close()
# print(ret)
View Code

二.一對多的表關係操做ForeginKey

1.建立一對多的表關係

#create_table_ForeginKey.py


# 一對多建表操做
from  sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import create_engine
from sqlalchemy import Column,Integer,String,ForeignKey
from sqlalchemy.orm import relationship


class School(Base):
    __tablename__ = 'school'
    id = Column(Integer,primary_key=True)
    name = Column(String(32))


class Student(Base):
    __tablename__ = 'student'
    id = Column(Integer,primary_key=True)
    name = Column(String(32))
    school_id = Column(Integer,ForeignKey("school.id"))
    stu2sch = relationship("School",backref="stu2sch")

engine = create_engine("mysql+pymysql://root:614615@127.0.0.1:3306/led?charset=utf8")

Base.metadata.create_all(engine)
View Code

2.增長數據

#curd_insert_ForeginKey.py

#添加數據
from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import Student,School,String,Integer,engine

Session = sessionmaker(engine)
db_session = Session()


# 正向的添加數據 relationship版本
sch_obj = School(name="清華")
sch_obj.stu2sch = [Student(name="李志強"),Student(name="李二短")]
db_session.add(sch_obj)
db_session.commit()
db_session.close()



#反向的添加數據 relationship版本
stu_obj = Student(name="龍龍",stu2sch=School(name="北大"))
db_session.add(stu_obj)
db_session.commit()
db_session.close()
View Code

3.修改操做

curd_update_ForeginKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import School,Student,String,Integer,engine

Session = sessionmaker(engine)
db_session = Session()

sch = db_session.query(School).filter(School.name == "清華").first()
# 查到學校的id,在學生表裏查到學生是龍龍的學生把學校id改爲察到的學校id
db_session.query(Student).filter(Student.name == "龍龍").update({"school_id":sch.id})
db_session.commit()
db_session.close()
View Code

4.查的操做

#curd_select_ForeginKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import School,Student,engine,String,Integer

Session = sessionmaker(engine)
db_session = Session()


#relationship正向查詢版本
stu = db_session.query(Student).all()
for i in stu:
    print(i.name,i.id,i.stu2sch.name)


# relationship反向查詢版本
sch = db_session.query(School).all()
for school in sch:
    for student in school.stu2sch:
        print(school.id,school.name,student.name)
View Code

5.delete

#curd_delete_ForeginKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import Student,School,String,Integer,engine

Session = sessionmaker(engine)
db_session = Session()

sch = db_session.query(School).filter(School.name == '北大').first()
print(sch.id)
db_session.query(Student).filter(Student.school_id == sch.id).delete()
db_session.commit()
db_session.close()
View Code

三。多對多表的操做

未完,待續

相關文章
相關標籤/搜索