Python连接MySql教程

1.在MySql下载安装最新版,下载安装教程网上自查

2.需要pip安装第三方包:

pip install websocket
pip install websocket-client
pip install flask-sqlalchemy
pip install flask

国内镜像源:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
    

3.新建一个MySql.py文件,代码如下:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# 创建 Flask 应用程序实例
app = Flask(__name__)

HOSTNAME = "#"
PORT = 3306
USERNAME = "#"
PASSWORD = "#"
DATABASE = "#"

# 配置数据库 URI
app.config[
    "SQLALCHEMY_DATABASE_URI"] = f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4'

# 配置 SQLAlchemy 引擎选项
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'pool_recycle': 280}

# 初始化 SQLAlchemy
db = SQLAlchemy(app)

with app.app_context():
    # 在应用上下文中执行数据库操作
    # 尝试创建一个新的表格
    try:
        db.create_all()
        # db.drop_all()
        print("数据库连接成功!")
    except Exception as e:
        print("数据库连接失败:", e)

# 你的代码......
    

4.值得推荐的免费MySql云服务:https://sqlpub.com/