###连接池使用
使用mysql的时候避免频繁申请mysql的连接造成不必要的开销,可以使用连接池进行避免
一,DBUtils库
import pymysql
from DBUtils.PooledDB import PooledDB
from common.setting import *
from common.single_design import single
#需要一个单列模式装饰器
@single
class MysqlPool(object):
def __init__(self):
self.pool = PooledDB(pymysql,10,**MYSQL_CONF)
def get_conn(self):
return self.pool.connection()
mysql_pool = MysqlPool()
conn = mysql_pool.get_conn()
二、mysql if语句的用法
from common.mysql_pool import conn
cursor = conn.cursor()
campus_id = 0
school_id = 0
school_name = ""
campus_name = ""
city = ""
title = "296"
sql = f"""
select * from old_goods a
left join campus_info b on a.school=b.id
left join school_info c on b.school=c.id
where if({campus_id}, b.id={campus_id}, 1=1) and
if({school_id}, c.id={school_id}, 1=1) and
c.school like "%{school_name}%" and
b.name like "%{campus_name}%" and
b.city like "%{city}%" and
a.title like "%{title}%"
"""
cursor.execute(sql)
datas = cursor.fetchall()