查询mysql数据库数据

import pymysql
from Com.myconf import conf


class MySql:
    def __init__(self):
        # (1)连接mysql数据库
        self.con = pymysql.Connect(
            host= conf.get('mysql', 'host'),  # 连接ip
            port=conf.getint('mysql', 'port'),  # 端口号
            user=conf.get('mysql', 'user'),  # 数据库用户名
            passwd=conf.get('mysql', 'passwd'),  # 数据库密码
            db=conf.get('mysql', 'db'),  # 数据库名
            charset='utf8'  # 设置了数据库的字符集
        )

        # (2)创建游标对象:用于执行SQL语句
        self.cursor = self.con.cursor()

    # (3)执行SQL语句
    def readone(self, sql):  # 显示查找的第一条数据
        self.con.commit() # 提交执行(执行完增删改数据后,需要提交)
        self.cursor.execute(sql)
        return self.cursor.fetchone()

    def readall(self, sql):  # 显示查找的所有内容(元组形式)
        self.con.commit()
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def count(self, sql):
        self.con.commit()
        return self.cursor.execute(sql)

    def close(self):
        self.cursor.close()  # 关闭游标对象
        self.con.close()  # 断开连接

    # 将查询的结果作为value,查询的字段作为键,转为dict格式
    def dictData(self,sql):
        self.readall(sql)
        col = []
        resultSets = []
        for i in self.cursor.description:
            col.append(i[0])

        for data in self.readall(sql):
            list2 = list(data)
            resultSets.append(dict(map(lambda x,y:[x,y],col,list2)))
        return resultSets





# 注意:不能在数据库中直接创建对象,在不同测试类中直接调用【因为测试完成后,需要关闭测试库,影响连接状态】
# 需对类数据进行操作的,在调用类中创建对象,不可在被调用的类中创建对象
# mysql = MySql()
if __name__ == '__main__':
    pass
原文地址:https://www.cnblogs.com/kite123/p/13995493.html