0%

Flask使用ORM连接数据库

注:使用前请安装flask_sqlalchemy包,由于python-mysql不适用于python3.6,所以我们使用pymysql进行替代


1.flask的app文件中输入以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(文件名为:learn_flask_mysql_orm.py)
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"]="mysql+pymysql://root:@127.0.0.1:3306/learn_flask_mysql"
#注:请勿忘记添加'+pymysql',否则将会出现没有安装mysqldb的报错

db = SQLAlchemy(app)


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


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

2.在flask文件夹中新建一个models.py文件,并输入以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
from learn_flask_mysql_orm import db

class User(db.Model):
__tablename__ = 'user'
user_id = db.Column(db.INT,primary_key=True)
user_name = db.Column(db.TEXT)

def __init__(self,user_id,user_name):
self.user_id = user_id
self.user_name = user_name

def __str__(self):
return "id:{} name:{}".format(self.user_id,self.user_name)

3.在flask中新建一个manage.py文件,输入以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from flask_script import Manager
from models import User
from learn_flask_mysql_orm import app,db

manager = Manager(app)

@manager.command
def save():
user = User(11,'zhangjia11')
db.session.add(user)
db.session.commit()

@manager.command
def query_all():
users = User.query.all()
for user in users:
print(user)

if __name__ == "__main__":
manager.run()

之后使用python manage.py save即可保存数据,使用python manage.py qurey_all即可查询数据