Environment:
Win10
python3.6
selenium2.53.1
Preparatory work: Install Pymysql first
python2.x linked database uses MYSQLDB, and python3.x linked database uses Pymysql
Pymysql Installation:
Method One: Perform the installation via PIP
1. Enter the Scripts directory (E:\Program files\python36\scripts)
2. Run the command pip install Pymysql
Mode two: Download the unpacking package for installation
1. Go to: Https://github.com/PyMySQL/PyMySQL, download
2. Extract the downloaded content into the Lib\site-packages directory (E:\Program files\python36\lib\site-packages)
3. Enter the file you just unzipped Pymysql (E:\Program files\python36\lib\site-packages\pymysql)
4. Run command installation: Python setup.py install
Implementation steps:
1. Create a database connection: Host is the database location, port is the database port, user is the login username, passwd for the login password, DB for table name, CharSet: Specify the database format such as: UTF8 (CharSet can not write)
def connects (self, host, port, user, passwd, DB, CharSet): # Link database, define account password and username = pymysql. Connect ( host=host, port=port, user=user, passwd=passwd, db=db, charset=charset )
2. Creating Cursors
def cureors (self): # Get cursor by connecting data = Self.connect.cursor ()
3. Return query results based on query statement and return in JSON format
def selects (self, sql=None): Print ("Back to Dictionary") Try: Self.cursor.execute (SQL) # appears to be a property of the Print field index=self.cursor.description Result=[] # Fetchall (): Receives all the returned result rows. forResinchSelf.cursor.fetchall (): Row={} # Range (x): from 0 to X, excluding X # len: Returns the length of a string, a list, a dictionary, a tuple, and so on forIinchRange (len (index)): # index[i][0] Gets the local information in the property in the field row[index[i][0]] =Res[i] Result.append (ROW) # Print ("selects_list%s"%row)returnresult; Except:print ('MySQL Connect fail ...')
4. Close link can't forget
def closes (self): # Close cursor self.cursor.close () # Close Library link self.connect.close ()
5. Start the link
if __name__=='__main__': PM= Pymysqls.__new__(PYMYSQLS)Pm.connects_cureors ('Load', 3306,'Root','123456','Table','UTF8') SQL="----';"result=pm.selects (SQL) pm.closes () data_list= Pm.obj_test (result, User_class ())
6. The closed instruction cannot be forgotten
def Closes (self): # Close Cursors self.cursor.close () # Close library link self.connect.close ()
7. Convert result after query to class object
7.1 First create a dictionary data_list to hold all objects
7.2for iterates through result data while creating a class object Test
7.3 Create a list of dictionaries to store test, but to extract the relationship of key-value pairs, to differentiate between uniqueness
7.4 Invoking a command to execute a transformation statement
7.5 Most key by ID of class object, whole class object as value
7.6 Finally add the list to the dictionary and return it
def obj_test (Self, result,obj): = [] for in Result: = obj = {} = Json.dumps (res, ensure_ascii=False) = json.loads (jsondatar) test. __dict__ = rebuild = test data_list.append (dictionaries) return data_list;
Overall Step Analysis:
1. Link Database
2. Creating Cursors
3. Save the results of the query in JSON format (dictionaries and lists are generally used)
Additional actions:
Convert JSON to string format
def json_str_dumps (self, result): # using Json.dumps to convert data to JSON format, the Json.dumps method will be output to this format by default "\u5377\u76ae\u6298\u6263", plus ensure_ascii=false, can prevent Chinese garbled. # JSON takes a completely language-independent text format, in fact most modern computer languages support them in some form. This makes it possible for a data format to be exchanged between programming languages that are also based on these constructs. # json.dumps () converts the raw data to JSON (where single quotes become double quotes), while Json.loads () converts JSON to raw data. Jsondatar = json.dumps (result, ensure_ascii=False) # Remove the end-to-end bracket return Jsondatar[1:len (Jsondatar)-1]
Do not write well, do not spray. Thank you...
python3.6 + selenium2.53.1 Query the database and convert the contents of each row in the returned content to a class object