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)
相关推荐
Eiceblue1 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550402 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂2 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP3 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@3 小时前
Python数据分析7
开发语言·python
在未来等你4 小时前
SQL进阶之旅 Day 21:临时表与内存表应用
sql·mysql·postgresql·database·temporary-table·memory-table·sql-optimization
老胖闲聊4 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点4 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI4 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
小Tomkk5 小时前
阿里云 RDS mysql 5.7 怎么 添加白名单 并链接数据库
数据库·mysql·阿里云