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)
相关推荐
电院工程师7 分钟前
SIMON64/128算法Verilog流水线实现(附Python实现)
python·嵌入式硬件·算法·密码学
熙客11 分钟前
Kubernetes是如何保证有状态应用数据安全和快速恢复的
mysql·云原生·容器·kubernetes
倔强的石头1062 小时前
KingbaseES:从兼容到超越,详解超越MySQL的权限隔离与安全增强
数据库·mysql·安全·金仓数据库
Python图像识别2 小时前
75_基于深度学习的咖啡叶片病害检测系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
python·深度学习·yolo
闲人编程2 小时前
Python游戏开发入门:Pygame实战
开发语言·python·游戏·pygame·毕设·codecapsule
小鸡毛程序员2 小时前
我在CSDN学MYSQL之----数据库基本概念和基本知识(下)
数据库·mysql
米花町的小侦探2 小时前
解决 GORM + MySQL 5.7 报错:Error 1067: Invalid default value for ‘updated_at‘
mysql
雍凉明月夜2 小时前
人工智能学习中深度学习之python基础之 类
python·学习
Geo_V3 小时前
OpenAI 大模型 API 使用示例
python·chatgpt·openai·大模型应用·llm 开发
Hello_WOAIAI3 小时前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python