Python is relatively simple to access mysql. For details, see my other article: Link to two mysql functions: Query and update. below is the encapsulation of common functions, you can directly copy the file. File Name: DBUtil. py #-*-encoding: utf8-*-@ author: crazyant.net @ version: 2013-10-22
Python is relatively simple to access mysql. For details, see my other article: Link to two mysql functions: Query and update. below is the encapsulation of common functions, you can directly copy the file. File Name: DBUtil. py #-*-encoding: utf8-*-''' @ author: crazyant.net @ version: 2013-10-22
Python is relatively simple to access mysql. For details, refer to my other article: Link
I usually use two mysql functions: Query and update. below is the encapsulation of common functions, which can be directly used after copying them.
File Name: DBUtil. py
#-*-Encoding: utf8-*-''' @ author: crazyant.net @ version: mysql common function '''import MySQLdbclass DB () encapsulated by 2013-10-22 (): def _ init _ (self, DB_HOST, DB_PORT, DB_USER, DB_PWD, DB_NAME): self. DB_HOST = DB_HOST self. DB_PORT = DB_PORT self. DB_USER = DB_USER self. DB_PWD = DB_PWD self. DB_NAME = DB_NAME self. conn = self. getConnection () def getConnection (self): return MySQLdb. connect (host = self. DB_HOST, # Set MYSQL address port = self. DB_PORT, # Set the port number user = self. DB_USER, # Set the user name passwd = self. DB_PWD, # Set Password db = self. DB_NAME, # Database Name charset = 'utf8' # sets the encoding) def query (self, sqlString): cursor = self. conn. cursor () cursor.exe cute (sqlString) returnData = cursor. fetchall () cursor. close () self. conn. close () return returnData def update (self, sqlString): cursor = self. conn. cursor () cursor.exe cute (sqlString) self. conn. commit () cursor. close () self. conn. close () if _ name __= = "_ main _": db = DB ('2017. 0.0.1 ', 3306, 'root', '', 'wordpress') print db. query ("show tables ;")
The usage method is the main function under the file. Use query to execute the select statement and obtain the result; or use update to perform insert and delete operations.
Original article address: A common class used by Python to access MySQL encapsulation. Thank you for sharing it with the original author.