创建型模式
1.单例者模式
import traceback
import pymysql
from dbutils.pooled_db import PooledDB
class MySQLHelper(object):
def __init__(self, host, port, dbuser, password, database):
self.pool = PooledDB(
creator=pymysql,
maxconnections=6,
mincached=2,
maxcached=5,
maxshared=3,
blocking=True,
maxusage=None,
setsession=[],
ping=0,
host=host,
port=int(port),
user=dbuser,
password=password,
database=database,
charset='utf8'
)
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls)
return cls._instance
def create_conn_cursor(self):
conn = self.pool.connection()
cursor = conn.cursor(pymysql.cursors.DictCursor)
return conn, cursor
def fetch_all(self, sql, args=None):
try:
conn, cursor = self.create_conn_cursor()
cursor.execute(sql, args)
res = cursor.fetchall()
cursor.close()
conn.close()
return res
except Exception:
print(traceback.format_exc())
def insert_one(self, sql, args=None):
try:
conn, cursor = self.create_conn_cursor()
res = cursor.execute(sql, args)
conn.commit()
print("记录数:" + str(res))
cursor.close()
conn.close()
return res
except Exception:
print(traceback.format_exc())
def insert_batch(self, sql, args=None):
try:
conn, cursor = self.create_conn_cursor()
res = cursor.executemany(sql, args)
conn.commit()
print("记录数:" + str(res))
cursor.close()
conn.close()
return res
except Exception:
print(traceback.format_exc())
def update(self, sql, args=None):
try:
conn, cursor = self.create_conn_cursor()
res = cursor.execute(sql, args)
conn.commit()
print("记录数:" + str(res))
cursor.close()
conn.close()
return res
except Exception:
print(traceback.format_exc())
def delete(self, sql, args=None):
try:
conn, cursor = self.create_conn_cursor()
res = cursor.execute(sql, args)
conn.commit()
print("记录数:" + str(res))
cursor.close()
conn.close()
return res
except Exception:
print(traceback.format_exc())
def my_function_vo(self, name, args=None):
try:
conn, cursor = self.create_conn_cursor()
cursor.callproc(name, args)
conn.commit()
cursor.close()
conn.close()
except Exception:
print(traceback.format_exc())
def mfunctionRe(self, name, args=None):
try:
conn, cursor = self.create_conn_cursor()
cursor.callproc(name, args)
conn.commit()
res = cursor.fetchall()
cursor.close()
conn.close()
return res
except Exception:
print(traceback.format_exc())
if __name__ == '__main__':
sql_helper = MySQLHelper("192.168.226.137", 3306, "root", "password", "test")
sql_helper1 = MySQLHelper("192.168.226.137", 3306, "root", "password", "test")
print(id(sql_helper))
print(id(sql_helper1))
rest = sql_helper.fetch_all("select * from article")
rest1 = sql_helper1.fetch_all("select * from article")
for i in rest:
print(i)
for i in rest1:
print(i)
定义:保证一个类只有一个实例,并提供一个访问它的全局访问点
优点
- 对唯一实例的受控访问
- 单例相当于全局变量,但防止了命名空间被污染