MYSQL类实现从数据库相应的表中获取所有属性及其数据,数据为元组类型。返回结果存放在字典中
import pymysql class MYSQL: def __init__(self): pass def __del__(self): self._cursor.close() self._connect.close() def connectDB(self): """ 连接数据库 :return: """ try: self._connect = pymysql.Connect( host=‘localhost‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘test‘, charset=‘utf8‘ ) return 1 except: return 0 def readObject(self, target): """ 读取评价对象 :return: list对象:所有的评价对象及其数据,数据的行数 """ self._cursor=self._connect.cursor() result = {} # {字段:该字段的所有值列表(包含字段)} name = [] # target表的所有字段的列表 data = () sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = ‘%s‘" name_sql = "select %s from %s" self._cursor.execute(sql % target) results = self._cursor.fetchall() for row in results: name.append(row[0]) # print(name) for i in name: self._cursor.execute(name_sql % (i, target)) data = self._cursor.fetchall() # Python 字典 setdefault() 函数 # 如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值 result.setdefault(i, data) return result, len(data) if __name__ == ‘__main__‘: mysql = MYSQL() flag = mysql.connectDB() if flag == 0: print(‘数据库连接失败‘) else: print(‘数据库连接成功‘) data, row_count = mysql.readObject(‘employee‘) print(data) print(row_count)
输出结果:
数据库连接成功 {‘FIRST_NAME‘: ((‘Mac‘,), (‘Marry‘,), (‘Bob‘,)), ‘LAST_NAME‘: ((‘Mohan‘,), (‘Mohan‘,), (‘Mohan‘,)), ‘AGE‘: ((20,), (32,), (21,)), ‘SEX‘: ((‘M‘,), (‘M‘,), (‘F‘,)), ‘INCOME‘: ((2000.0,), (3000.0,), (4000.0,))} 3
原文地址:https://www.cnblogs.com/fuqia/p/8994681.html
时间: 2024-10-10 15:29:05