Python项目Flask框架整合Mysql

一、在配置类中编写Mysql配置信息

二、实现Mysql配置类

python 复制代码
import pymysql
from config.config import MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_PROT, MYSQL_DB, MYSQL_CHARSET


class MysqlDB():
    def __init__(self, MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_PROT, MYSQL_DB, MYSQL_CHARSET):
        self.mysql = pymysql.connect(
            host=MYSQL_HOST,  # 连接名称,默认127.0.0.1
            user=MYSQL_USER,  # 用户名
            passwd=MYSQL_PASSWD,  # 密码
            port=MYSQL_PROT,  # 端口,默认为3306
            db=MYSQL_DB,  # 数据库名称
            charset=MYSQL_CHARSET,  # 字符编码
        )
    def get(self):
        self.mysql.ping(reconnect=True)
        cursor = self.mysql.cursor()
        # 执行一个简单的SELECT语句
        cursor.execute("select * from test")
        # 获取结果
        results = cursor.fetchall()
        cursor.close()
        return  results

    def get_index_by_id(self,id):
        self.mysql.ping(reconnect=True)
        cursor = self.mysql.cursor()
        # 执行一个简单的SELECT语句
        cursor.execute(f"select * from test where id  = {id}")
        # 获取结果
        results = cursor.fetchall()
        cursor.close()
        return results


mysql_db = MysqlDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_PROT, MYSQL_DB, MYSQL_CHARSET)

三、在目标文件中引用并使用

python 复制代码
from config.MysqlConfig import mysql_db

"""
测试专用
"""
@bi.route('/ssss', methods=['GET'])
def get_test():

    result = mysql_db.get();
    print(result)
相关推荐
Gigavision5 小时前
基于BUAA-MIHR数据集的噪声解耦对比学习算法
人工智能·python·深度学习·算法
IPdodo_5 小时前
跨境 API 调用不稳定怎么办:出口、超时重试与链路监控的实践
网络·python·网络协议
Madison-No76 小时前
搭建项目测试环境
linux·运维·服务器·python
计算机编程-吉哥6 小时前
YOLO26 vs YOLO11 vs YOLOv8:深度学习咖啡果实成熟度分割系统【计算机毕业设计选题推荐】
人工智能·python·深度学习·yolo·django·毕业设计
大衛說7 小时前
11 · 异常处理与日志
python
auto_go7 小时前
Python 实战指南(7)——账本动不动就崩?先把“魔法字符串”和“裸报错”干掉
python
Beyond_System|系统之外7 小时前
【学编程】Python基础编程题100道(21-60)
开发语言·python·算法
根目录下的猫7 小时前
RK3588适配的轻量级AI模型推荐
人工智能·后端·python·目标检测
wno7048 小时前
Spring Security权限控制
java·python·spring
ShineWinsu9 小时前
对于Coze—AI:SDK的解析
人工智能·python·ai·sdk·项目·coze·字节跳动