mysql数据库连接:返回list和dict格式

import pymysql
from api.conf.setting import mysql_info
class HandleDb:
    def __init__(self):
        # 连接数据库
        self.conn = pymysql.connect(host=mysql_info["host"],  # mysql服务器ip或者域名
                                    user=mysql_info["user"],  # 用户名
                                    password=mysql_info["password"],  # 密码
                                    db=mysql_info["db"],  # 连接的数据库名
                                    autocommit=True,  # 自动提交连接对象
                                    port=3306,  # 数据库端口号
                                    charset='utf8',  # 数据库编码为utf8,不能写为utf-8
   # 默认返回的结果为元祖或者嵌套元祖的列表
   # 可以指定cursorclass为DictCursor,那么返回的结果为字典或者嵌套字典的列表
                                    cursorclass=pymysql.cursors.DictCursor
                                    )
        # 2、创建游标对象
        self.cursor = self.conn.cursor()
    # 查询结果value的值将其生成列表
    def get_data(self, sql):
        value_list = []
        # 3、使用游标对象执行sql语句
        self.cursor.execute(sql)
        # 4、使用fetchall获取所有结果,返回的是嵌套字典的字典
        result = self.cursor.fetchall()
        # self.cursor.fetchone()
        for key in result:
            for val in key.values():
                value_list.append(val)
        return value_list
    def get_data_dict(self, sql):
        # 3、使用游标对象执行sql语句
        self.cursor.execute(sql)
        # 4、使用fetchall获取所有结果,返回的是嵌套字典的字典
        result = self.cursor.fetchall()
        return result
    # 6、一定要关闭游标和连接
    # 先关闭游标对象,然后关闭连接对象
    def db_close(self):
        # 关闭游标
        self.cursor.close()
        # 关闭连接
        self.conn.close()
# 实例化用于关闭数据库连接
mysql = HandleDb()
if __name__ == '__main__':
    cl = HandleDb()
    # sql = "select * from tz_attach_file where file_path ='2024/03/c2876474841b479dab280a9b1cfc63a2.png'"
    sql = "select mobile_code from tz_sms_log where user_phone = '18711277355' order by id desc limit 1"
    print(cl.get_data_dict(sql), type(cl.get_data_dict(sql)))
    cl.db_close()

 

posted on 2024-04-06 19:44  诚实的表达自己  阅读(52)  评论(0编辑  收藏  举报