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)
相关推荐
站大爷IP几秒前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
得物技术2 小时前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
xiaok2 小时前
mysql中怎么创建一个可控权限数据库账号密码给到开发者
mysql
用户8356290780515 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i6 小时前
python中类的基本结构、特殊属性于MRO理解
python
ByteBlossom6 小时前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
玉衡子6 小时前
九、MySQL配置参数优化总结
java·mysql
liwulin05066 小时前
【ESP32-CAM】HELLO WORLD
python
-Xie-6 小时前
Mysql杂志(十六)——缓存池
数据库·mysql·缓存
Doris_20236 小时前
Python条件判断语句 if、elif 、else
前端·后端·python