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)
相关推荐
2501_908329855 分钟前
使用Python自动收发邮件
jvm·数据库·python
2501_9083298536 分钟前
NumPy入门:高性能科学计算的基础
jvm·数据库·python
ahauedu1 小时前
MySQL 8.0+ 默认使用 caching_sha2_password 插件进行密码加密
数据库·mysql
2401_874732531 小时前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
平常心cyk1 小时前
Python基础快速复习——集合和字典
开发语言·数据结构·python
阿钱真强道2 小时前
34 Python 离群点检测:什么是离群点?为什么要做异常检测?
python·sklearn·异常检测·异常·离群点检测
AC赳赳老秦2 小时前
OpenClaw关键词挖掘Agent配置(附SOP脚本,可直接复制使用)
java·大数据·开发语言·人工智能·python·pygame·openclaw
qq_416018722 小时前
数据分析与科学计算
jvm·数据库·python
深藏功yu名2 小时前
Day24(进阶篇):向量数据库 Chroma_FAISS 深度攻坚 —— 索引优化、性能调优与生产级落地
数据库·人工智能·python·ai·agent·faiss·chroma
_evenif2 小时前
MySql 8 一机多实例部署
linux·数据库·mysql