import pymysql
class MysqlConnection(object):
def __init__(self, config):
self.connection = pymysql.connect(**config)
self.connection.autocommit(True)
self.cursor = self.connection.cursor()
def reConnect(self):
"""
重连机制
:return:
"""
try:
self.connection.ping()
except:
self.connection()
def close(self):
"""
断开连接
:return:
"""
self.cursor.close()
self.connection.close()
def __del__(self):
self.close()
def queryAll(self, sql):
"""
查询所有数据
:param sql: sql语句
:return:
"""
self.reConnect()
try:
self.cursor.execute(sql)
return self.cursor.fetchall()
except Exception as e:
return e
def queryMany(self, sql, n):
"""
查询几条数据
:param sql:
:return:
"""
self.reConnect()
try:
self.cursor.execute(sql)
return self.cursor.fetchmany(n)
except Exception as e:
return e
def queryOne(self, sql):
"""
查询一条记录
:param sql:
:return:
"""
self.reConnect()
try:
self.cursor.execute(sql)
return self.cursor.fetchone()
except Exception as e:
return e
def operate(self, sql, params=None, DML=True):
"""
"""
self.reConnect()
try:
with self.connection.cursor() as cursor:
cursor.execute(sql, params)
self.connection.commit()
return 0
except Exception as e:
if DML:
self.connection.rollback()
return e
if __name__ == "__main__":
# 举个例子
config = {
'host':'192.168.153.32',
'port':3306,
'user':'root',
'password':'123456',
'db':'webapp'
}
msc = MysqlConnection(config)
sql = "select * from students"
print(msc.queryAll(sql))