python3 flask 使用Mysql数据库
创建flask基本项目结构
from flask import Flask app = Flask(__name__)安装
flask-sqlalchemypip install flask-sqlalchemy导入配置
from flask_sqlalchemy import SQLAlchemy app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/hhh' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app)python3 不再支持MySQKdb,连接mysql数据库需要使用pymysql
安装pymysql
pip install pymysql定义表模型
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, nullable=True) def __init__(self, username): self.username = username def __repr__(self): return '<User {}>'.format(self.username)创建表
在python shell中>>> from app import db >>> db.create_all()添加数据
在python shell中>>> from app import db >>>
这篇博客介绍了如何在Python3的Flask应用中使用MySQL数据库,包括安装pymysql,定义表模型,创建和操作数据,以及实现一对多、一对一和多对多表关联。还提供了创建RESTful接口的示例源代码。
最低0.47元/天 解锁文章
67

被折叠的 条评论
为什么被折叠?



