The MySQL class implements fetching all properties and their data from the corresponding table in the database, which is the tuple type. Return results stored in the dictionary
ImportPymysqlclassMYSQL:def __init__(self):Pass def __del__(self): Self._cursor.close () self._connect.close ()defConnectdb (self):"""Connect to database: return:""" Try: Self._connect=Pymysql. Connect (Host='localhost', Port=3306, the user='Root', passwd='123456', DB='Test', CharSet='UTF8' ) return1except: return0defreadobject (self, target):"""Read Evaluation object: Return:list object: All the evaluated objects and their data, the number of rows of data"""Self._cursor=self._connect.cursor () result= {}#{field: List of all values for this field (contains fields)}name = []#List of all fields of the target tabledata =() 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 () forRowinchresults:name.append (row[0]) #Print(name) forIinchName:self._cursor.execute (Name_sql%(i, target)) data=Self._cursor.fetchall ()#Python dictionary setdefault () function #If the dictionary contains a given key, the value corresponding to the key is returned, otherwise the value set for the key is returned .Result.setdefault (i, data)returnresult, Len (data)if __name__=='__main__': MySQL=MYSQL () flag=Mysql.connectdb ()ifFlag = =0:Print('Database connection Failed') Else: Print('Database Connection succeeded') data, Row_count= Mysql.readobject ('Employee') Print(data)Print(Row_count)
Output Result:
database connection succeeded {'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
MySQL gets all the property names and their data for a table