乐趣区

关于mysql:PythonFlaskMySQL-连接数据库

一、筹备

  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):
        return '<Role %r>' %self.name

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(Role.id)) # 外键

    def __repr__(self): #toString
        return '<User %r>' %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

退出移动版