3.Flask-SQLAlchemy

 (1)安裝

pip install flask_sqlalchemy

(2)數據庫鏈接

from flask import Flask
# 1.導入
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
#2.定義要鏈接的數據庫
DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
#3.添加到到配置中
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =False
# 4.實例化一個對象,將app傳進去 db = SQLAlchemy(app) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()

(3)建立表

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(50),nullable=False)


class Article(db.Model):
    __tablename__ = "article"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(50), nullable=False)
    uid = db.Column(db.Integer,db.ForeignKey("user.id"))
    author = db.relationship("User",backref='article')

db.drop_all()         #刪除表
db.create_all()       #建立表


@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

(4)添加數據

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(50),nullable=False)


class Article(db.Model):
    __tablename__ = "article"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(50), nullable=False)
    uid = db.Column(db.Integer,db.ForeignKey("user.id"))
    author = db.relationship("User",backref='article')

# db.drop_all()         #刪除表
# db.create_all()       #建立表

#添加數據
user = User(username='derek')
article = Article(title='今天5/27號')
article.author = user

db.session.add(article)
db.session.commit()


@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

(5)查看、修改和刪除

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(50),nullable=False)

    def __repr__(self):
        return "<username:%s>"%self.username

class Article(db.Model):
    __tablename__ = "article"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(50), nullable=False)
    uid = db.Column(db.Integer,db.ForeignKey("user.id"))
    author = db.relationship("User",backref='article')

# db.drop_all()         #刪除表
# db.create_all()       #建立表

# 1.添加數據
# user = User(username='derek')
# article = Article(title='今天5/27號')
# article.author = user
#
# db.session.add(article)
# db.session.commit()

# 2.查詢數據
# users=User.query.all()
# print(users)

# 3.修改數據,先查找出來再修改
# user = User.query.filter(User.username=='derek').first()
# user.username = 'jack'
# db.session.commit()

# 4.刪除數據
user = User.query.filter(User.username=='jack').first()
db.session.delete(user)
db.session.commit()

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

 

 

 

 

SQLAlchemy 沒有 Django 的 Models 好用html

我在這裏官宣闢謠一下啊, Models 牢牢只是配置和使用比較簡單(這特麼就是廢話),由於他是Django自帶的ORM框架,也正是由於是Django原生的,因此兼容性遠遠不如SQLAlchemymysql

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

固然了,不管是使用什麼ORM框架,都是爲了方便不熟練數據庫的同窗使用的,我我的仍是比較推崇原生 SQL ,也建議每位同窗攻克 SQL 的難關數據庫

廢話很少說,咱們來看一下 SQLAlchemy 如何使用:flask

單表操做:session

1.建立app

建立基類和第一張數據表

2.增刪改查相關操做:框架

增刪改查

3.搞基高几高技告急膏劑高集高吉高級版查詢操做ide

 1 from CreateDB import Users, School
 2 
 3 # 1. 建立一個用戶添加到數據庫
 4 # 建立鏈接
 5 from sqlalchemy import create_engine
 6 from sqlalchemy.orm import sessionmaker
 7 engine = create_engine("mysql+pymysql://root:DragonFire@127.0.0.1:3306/dragon?charset=utf8",
 8                        )
 9 
10 # 建立數據表操做對象 sessionmaker
11 DB_session = sessionmaker(engine)
12 db_session = DB_session()
13 
14 # 查詢數據表操做
15 """
16 r1 = session.query(Users).all()
17 r2 = session.query(Users.name.label('xx'), Users.age).all()
18 r3 = session.query(Users).filter(Users.name == "alex").all()
19 r4 = session.query(Users).filter_by(name='alex').all()
20 r5 = session.query(Users).filter_by(name='alex').first()
21 r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(Users.id).all()
22 r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()
23 """
24 # 篩選查詢列
25 # user_list = db_session.query(Users.name).all()
26 # print(user_list) # [('alexDSB',), ('zhangsan',)] 雖然看到的是元祖,可是依然能夠經過對象打點兒調用屬性
27 # for row in user_list:
28 #     print(row.name)
29 
30 # 別名映射  name as nick
31 # user_list = db_session.query(Users.name.label("nick")).all()
32 # print(user_list) # [('alexDSB',), ('zhangsan',)] 雖然看到的是元祖,可是依然能夠經過對象打點兒調用屬性
33 # for row in user_list:
34 #     print(row.nick) # 這裏要寫別名了
35 
36 # 篩選條件格式
37 # user_list = db_session.query(Users).filter(Users.name == "alexDSB").all()
38 # user_list = db_session.query(Users).filter(Users.name == "alexDSB").first()
39 # user_list = db_session.query(Users).filter_by(name="alexDSB").first()
40 # for row in user_list:
41 #     print(row.nick)
42 
43 # 複雜查詢
44 # from sqlalchemy.sql import text
45 # user_list = db_session.query(Users).filter(text("id<:value and name=:name")).params(value=3,name="alexDSB")
46 
47 # 查詢語句
48 # from sqlalchemy.sql import text
49 # user_list = db_session.query(Users).filter(text("select * from users id<:value and name=:name")).params(value=3,name="alexDSB")
50 
51 # 排序 :
52 # user_list = db_session.query(Users).order_by(Users.id).all()
53 # user_list = db_session.query(Users).order_by(Users.id.desc()).all()
54 # for row in user_list:
55 #     print(row.name,row.id)
56 
57 #其餘查詢條件
58 """
59 ret = session.query(Users).filter_by(name='alex').all()
60 ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
61 ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all() # between 大於1小於3的
62 ret = session.query(Users).filter(Users.id.in_([1,3,4])).all() # in_([1,3,4]) 只查詢id等於1,3,4的
63 ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all() # ~xxxx.in_([1,3,4]) 查詢不等於1,3,4的
64 ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all() 子查詢
65 from sqlalchemy import and_, or_
66 ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
67 ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
68 ret = session.query(Users).filter(
69     or_(
70         Users.id < 2,
71         and_(Users.name == 'eric', Users.id > 3),
72         Users.extra != ""
73     )).all()
74 # select * from users where id<2 or (name="eric" and id>3) or extra != "" 
75 """
76 
77 # 關閉鏈接
78 db_session.close()
高級版查詢操做

4.高級版更新操做post

高級版更新操做

5.擴展內容

排序分組選取通配符

 

一對多的操做 : ForeignKey

1.建立表:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship

#建立基類,至關於Django中的 models.Model,被各個數據表類所繼承
Base = declarative_base()


# ##################### 多表示例 #########################
# 建立一張數據表
class Author(Base):
    __tablename__ = 'author'

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True)


#  建立另外一張數據表
class Book(Base):
    __tablename__ = 'book'

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True)

    author_id = Column(Integer,ForeignKey("author.id"))

    # relationshi 不會單獨生成字段 ,只用於增長查詢操做
    user = relationship("Author",backref="author2book") # backref 反向查找的名字




# 建立數據庫連接
engine = create_engine(
        "mysql+pymysql://root:DragonFire@localhost:3306/dragon?charset=utf8",
        max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
        pool_size=5,  # 鏈接池大小
        pool_timeout=30,  # 池中沒有線程最多等待的時間,不然報錯
        pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
    )

# 經過Base.metadata找到全部繼承 Base 的數據表class
Base.metadata.create_all(engine)
建立多表並創建關係

2.增刪改查

 1 from SQLAlchemy_ready.ss2_ForeignKey_relationship import Author, Book
 2 
 3 # 1. 建立一個用戶添加到數據庫
 4 # 建立鏈接
 5 from sqlalchemy import create_engine
 6 from sqlalchemy.orm import sessionmaker
 7 engine = create_engine("mysql+pymysql://root:DragonFire@127.0.0.1:3306/dragon?charset=utf8",
 8                        )
 9 
10 # 建立數據表操做對象 sessionmaker
11 DB_session = sessionmaker(engine)
12 db_session = DB_session()
13 
14 # 1.增長 操做數據表
15 # 添加兩個做者:
16 # db_session.add_all([
17 #     Author(name="alex"),
18 #     Author(name="yinwangba")
19 # ])
20 # db_session.commit()
21 # 添加一本書 jinpingmei 做者是 yinwangba
22 # author = db_session.query(Author).filter(Author.name == "yinwangba").first()
23 # db_session.add(Book(name="jinpingmei",author_id=author.id))
24 # db_session.commit()
25 
26 # 2.查詢全部數據,並顯示做者名稱,連表查詢
27 # book_list = db_session.query(Book).all()
28 # for row in book_list:
29 #     print(row.name,row.author_id)
30 
31 # book_list = db_session.query(Book.name.label("bname"),Author.name.label ("aname")).join(Author,Book.author_id == Author.id,isouter=True).all()
32 # print(book_list)
33 # for row in book_list:
34 #     print(row.aname,row.bname)
35 
36 # 查詢之relationship 快速連表
37 # 建立表的時候加入 relationship
38 #普通版添加
39 # obj = Author(name="yinwangba")
40 # db_session.add(obj)
41 # db_session.commit()
42 # print(obj.id,obj.name)
43 #
44 # obj_book = Book(name="jinpingmei",author_id=obj.id)
45 # db_session.add(obj_book)
46 # db_session.commit()
47 # obj = Author(name="yinwangba")
48 
49 # relationship版 添加
50 # bobj = Book(name="jinpingmei",user=Author(name="yinwangba"))
51 # db_session.add(bobj)
52 # db_session.commit()
53 
54 # 查詢之relationship 快速連表
55 # book_list = db_session.query(Book).all()
56 # for row in book_list:
57 #     print(row.name,row.user.name)
58 
59 # 查詢做者的全部書籍
60 # obj = db_session.query(Author).filter(Author.name=="yinwangba").first()
61 # print(obj.author2book)
62 
63 # 反向字段添加
64 # author_obj = Author(name="alex")
65 # author_obj.author2book = [Book(name="儒林外史之銀林大戰"),Book(name="鄰家小妹妹")]
66 # db_session.add(author_obj)
67 # db_session.commit()
68 
69 # 關閉鏈接
70 db_session.close()
增刪改查

 

多對多 : ManyToMany

1.建立表

 1 import datetime
 2 from sqlalchemy import create_engine
 3 from sqlalchemy.ext.declarative import declarative_base
 4 from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
 5 from sqlalchemy.orm import relationship
 6 
 7 #建立基類,至關於Django中的 models.Model,被各個數據表類所繼承
 8 Base = declarative_base()
 9 
10 # 建立第三張表 Boys and Girls
11 class Hotel(Base):
12     __tablename__ = "hotel"
13 
14     id = Column(Integer,primary_key=True)
15     boy_id = Column(Integer,ForeignKey("boys.id"))
16     girl_id = Column(Integer,ForeignKey("girls.id"))
17 
18 # 建立一張數據表
19 class Boys(Base):
20     __tablename__ = 'boys'
21 
22     id = Column(Integer, primary_key=True)
23     name = Column(String(32), index=True)
24 
25     # 建立於酒店的關係
26     girls = relationship("Girls",secondary="hotel",backref="boys")
27 
28 # 建立另外一張數據表
29 class Girls(Base):
30     __tablename__ = "girls"
31 
32     id = Column(Integer,primary_key=True,autoincrement=True)
33     name = Column(String(32),index  =True)
34 
35     # 建立於酒店的關係
36     # boy = relationship("Boys",secondary="hotel",backref="toHotel")
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 # 建立數據庫連接
47 engine = create_engine(
48         "mysql+pymysql://root:DragonFire@localhost:3306/dragon?charset=utf8",
49         max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
50         pool_size=5,  # 鏈接池大小
51         pool_timeout=30,  # 池中沒有線程最多等待的時間,不然報錯
52         pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
53     )
54 
55 # 經過Base.metadata找到全部繼承 Base 的數據表class
56 Base.metadata.create_all(engine)
57 
58 
59 # SQLAlchemy數據表進行修改後,沒法直接進行更新,只能刪除表後進行操做,從新進行操做,
60 # 但Flask-SQLAlchemy + Flask-migrate + Flask-script 就能夠實現 Django 的數據遷移 MakeMigration migrate
61 
62 #
多對多關係創建

2.操做

 1 from SQLAlchemy_ready.ss4_M2M import Girls, Boys,Hotel
 2 
 3 # 1. 建立一個用戶添加到數據庫
 4 # 建立鏈接
 5 from sqlalchemy import create_engine
 6 from sqlalchemy.orm import sessionmaker
 7 engine = create_engine("mysql+pymysql://root:DragonFire@127.0.0.1:3306/dragon?charset=utf8")
 8 
 9 
10 # 建立數據表操做對象 sessionmaker
11 DB_session = sessionmaker(engine)
12 db_session = DB_session()
13 
14 # 1.增長 操做數據表
15 # boy = Boys(name="jinwangba")
16 # boy.girls = [Girls(name="fengjie"),Girls(name="juaner")]
17 # db_session.add(boy)
18 # db_session.commit()
19 
20 # 2.查詢
21 # 使用relationship正向查詢
22 # boy = db_session.query(Boys).first()
23 # print(boy.name,boy.girls[0].name)
24 
25 # 使用relationship反向查詢
26 # girls = db_session.query(Girls).first()
27 # print(girls.boys[0].name , girls.name)
28 
29 
30 # 關閉鏈接
31 db_session.close()
多對多操做

 

 

 

https://www.cnblogs.com/wupeiqi/articles/8259356.html

相關文章
相關標籤/搜索