Python+Flask+MySQL 连接数据库

一、准备

  1. 安装MySQL:MySQL安装
  2. 安装所需Python库

    pip install flask
    pip install flask-sqlalchemy
    pip install pymysql

二、编写Python代码

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app=Flask(__name__)

app.config['SECRET_KEY']='2333' # 密码
app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:2333@localhost:3306/runoob'
    # 协议:mysql+pymysql
    # 用户名:root
    # 密码:2333
    # IP地址:localhost
    # 端口:3306
    # 数据库名:runoob #这里的数据库需要提前建好
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
db=SQLAlchemy(app)

# 新建表Role
class Role(db.Model):
    __tablename__='roles' # 表名
    id=db.Column(db.Integer, primary_key=True) # id字段,int类型,主键
    name=db.Column(db.String(64), unique=True) # name字段,字符串类型,唯一
    users=db.relationship('User', backref='role', lazy='dynamic') # 外键关系,动态更新

    def __repr__(self): # 相当于toString
        return '' %self.name

# 新建表User
class User(db.Model):
    __tablename__='users'
    id=db.Column(db.Integer, primary_key=True)
    username=db.Column(db.String(64), unique=True, index=True) #索引
    role_id=db.Column(db.Integer, db.ForeignKey('roles.id')) # 外键

    def __repr__(self):
        return '' %self.username

if __name__=='__main__':
    db.drop_all() # 删除存在表
    db.create_all() # 创建这两个表
    app.run()

运行即可。运行成功的结果如下:

 * Serving Flask app "HelloMysql" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

三、查看数据库

mysql> SHOW DATABASES;
mysql> use RUNOOB;  //数据库名
mysql> SHOW TABLES;

即可看到创建表成功:

+------------------+
| Tables_in_runoob |
+------------------+
| roles            |
| users            |
+------------------+

四、参考

中国传媒大学《数据可视化》课时33

你可能感兴趣的:(Python+Flask+MySQL 连接数据库)