MySQL gets all the property names and their data for a table

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.