# 环境 python3.7
# 第三方库安装:
pip install pymysql
pip install DBUtils
# 功能实现:建立mysql连接池,实现增删查改
import pymysql
import time
from DBUtils.PooledDB import PooledDB
class MysqldbHelper(object): # 继承object类所有方法
def __init__(self, config):
self.host = config['host']
self.username = config['user']
self.password = config['passwd']
self.db = config['db']
self.port = config['port']
while True:
try:
self.pool = PooledDB(pymysql, 5, host=self.host, user=self.username, passwd=self.password, db=self.db,
port=self.port,
cursorclass=pymysql.cursors.DictCursor)
except BaseException as e:
print(e)
self.pool = None
if self.pool:
print("mysql连接成功")
break
print("连接失败,5秒后重试")
time.sleep(5)
# # 从连接池获取一条连接
def get_conn(self):
conn = self.pool.connection()
cur = conn.cursor() # 光标
return conn, cur
# 关闭连接
def close_conn(self, conn, cur):
cur.close()
conn.close()
def deal_with_sql(self, cur, conn, SQL, types='SELECT'):
if types == "SELECT":
cur.execute(SQL)
result = cur.fetchall()
return result
elif types == "INSERT":
try:
cur.execute(SQL)
conn.commit() # 提交事务
return True
except BaseException as e:
print("插入失败:", e)
return False
elif types == "UPDATE":
try:
cur.execute(SQL)
conn.commit()
return True
except BaseException as e:
print("更新失败:", e)
return False
elif types == "DELETE":
try:
cur.execute(SQL)
conn.commit()
return True
except BaseException as e:
print("删除失败:", e)
return False
else:
return None
if __name__ == '__main__':
config = {
'host': '47.103.1.124',
'port': 3306,
'user': 'root',
'passwd': '123456',
'db': '37',
}
# 初始化工具类
mydb = MysqldbHelper(config)
# 从连接池获取连接
conn, cur = mydb.get_conn()
# 执行查询sql
SQL = """select * from ceshi2"""
result = mydb.deal_with_sql(cur, conn, SQL)
print(result)
# 执行插入sql
SQL2 = """INSERT INTO ceshi2 (a,b,c) VALUES (12,11,34)"""
result2 = mydb.deal_with_sql(cur, conn, SQL2, "INSERT")
print(result2)
# 关闭连接
mydb.close_conn(conn, cur)
print("连接已关闭")
来源:oschina
链接:https://my.oschina.net/u/4323755/blog/4470114