-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.py
More file actions
128 lines (75 loc) · 2.58 KB
/
sql.py
File metadata and controls
128 lines (75 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# -*- encoding: utf-8 -*-
# @Contact : ynatsu233@outlook.com
# @Time : 4/27/2019 10:49 AM
# @Author : Natsu Yuki
# pip install mysqlclient
# pip install flask_sqlalchemy
from flask import *
from flask_sqlalchemy import SQLAlchemy
import config
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app=app)
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), nullable=False)
# article 与 tag 表 多对多联系
article_tag = db.Table(
'article_tag',
db.Column('article_id', db.Integer, db.ForeignKey('article.id'), primary_key=True),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
# 外键 一对多
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
author = db.relationship('User', backref=db.backref('articles'))
# 可进行如下创建
# a = Article(title='a', content='b')
# a.author = User.query.filter(User.id == 1).first()
# 多对多
tags = db.relationship('Tag', secondary=article_tag, backref='articles')
# 可进行如下创建
# article1.tags.append(tag1)
class Tag(db.Model):
__tablename__ = 'tag'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), nullable=False)
db.create_all()
def add():
a = Article(title='aaa', content='bbb')
db.session.add(a)
db.session.commit()
def search():
# 单表查询
s = Article.query.filter(Article.id == 1)
print(s)
# SELECT article.id AS article_id, article.title AS article_title, article.content
# AS article_content FROM article WHERE article.id = % s
a = s.all()[0] # a = s.first()
print(a.title, a.content)
# aaa bbb
# 多表查询
# 必需设置 relationship
# Article => User
a = Article.query.filter(Article.id == 1).first()
print(a.author.name)
# User => Article
u = User.query.filter(User.id == 1).first()
print(u.articles)
def modify():
article = Article.query.filter(Article.id == 1).first()
article.title = 'ccc'
db.session.commit()
def delete():
article = Article.query.filter(Article.id == 1).first()
db.session.delete(article)
db.session.commit()
@app.route('/')
def index():
return 'Hello world'
app.run()