Example Analysis of mysql Database encapsulated by third Party Library in Python
This article shows you the Python third-party library package mysql database sample analysis, concise and easy to understand, absolutely can make you shine, through the detailed introduction of this article I hope you can gain something.
This time the database is encapsulated, even if it is not for automated testing, database operations must also be able to, why? Because in many cases, repairing existing network user data is achieved through scripts, if you don't use other languages, then Python's advantage in this area is very obvious.
'''
Created on October 10, 2019
@author: qguan
'''
import pymysql
from utils.HandleLogging import log as logging
mysql_info = {"host": '127.0.0.1',
"port": 3306,
"user": 'root',
"passwd": 'root',
"db": 'mysql',
"charset": 'utf8'}
class HandleMySQL(object):
'''
classdocs
'''
def __init__(self):
'''
Initialize mysql database information, create connection cursors
'''
self.db_info = mysql_info
self.logger = logging
try:
self.conn = pymysql.connect(host=self.db_info['host'],
port=self.db_info['port'],
user=self.db_info['user'],
passwd=self.db_info['passwd'],
db=self.db_info['db'],
charset=self.db_info['charset'],
cursorclass=pymysql.cursors.DictCursor)
self.logger.info("success! ")
except Exception as a:
self.logger.info("failture:%s" % a)
raise a
else:
self.logger.info("create cursor! ")
self.cursor = self.conn.cursor()
def __call__(self, sql, arg=None, is_more=False):
'''
invoke database execution method
:param sql: sql statement executed, str type
:param arg: Parameter must be sequence type: list, str, tuple
:param is_more: Whether the query displays more data, usually determined by the limit of sql
:return:
'''
self.mysql_execute(sql, arg)
if is_more:
result = self.cursor.fetchall()
else:
result = self.cursor.fetchone()
#Not suitable, if there is sql in the loop execution, close here, will cause sql execution failure
# self.mysql_close()
return result
def mysql_execute(self, sql, arg=None):
'' Zhengzhou abortion hospital which is good http://mobile.zhongyuan120.com/
Encapsulate methods that execute sql statements themselves
'''
try:
self.cursor.execute(sql)
except Exception as a:
self.conn.rollback() # sql rollback processing
self.logger.info ("rollback sql, exception as follows: {}".format(a))
raise a
else:
self.conn.commit() # sql commit
def mysql_getrows(self, sql):
'''
Return query result set
:return: Returns a tuple of nested dictionaries
'''
try:
self.cursor.execute(sql) # arg must be a sequence type
except Exception as a:
self.logger.info ("Exception executing SQL statement: %s" % a)
raise a #throws an exception directly without executing the following statement
else:
rows = self.cursor.fetchall()
return rows
def mysql_getrow(self, sql):
'''
Return query result set
return: The result is a dictionary
'''
try:
self.cursor.execute(sql) # arg must be a sequence type
except Exception as a:
self.logger.info ("Exception executing SQL statement: %s" % a)
raise a
else:
row = self.cursor.fetchone()
return row
def mysql_close(self):
'''
Close database connection, close cursor
'''
try:
self.conn.close()
self.cursor.close()
self.logger.info ("Close mysql connection normally! ")
except Exception as a:
self.logger.info ("Failed to close mysql connection pool, exception as follows: {}".format(a))
raise a
if __name__ == '__main__':
mq = HandleMySQL()
sql = 'SELECT *from user limit 3'
# print(mq(sql, is_more=True))
mq.mysql_close()
The above content is an example analysis of a third-party library encapsulating mysql database in Python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserves, please pay attention to the industry information channel.