python
复制代码
import pymysql
class DB:
localhost = {
'host': 'localhost',
'user': 'root',
'password': 'ccc3#dd599',
'database': 'test'
}
dev = {
'host': 'localhost',
'user': 'root',
'password': 'ccc3#dd599',
'database': 'test'
}
def __init__(self, env):
print("初始化方法调用.....")
self.dev = DB.dev
self.localhost = DB.localhost
if env == 'localhost':
self.connection = pymysql.connect(host=self.localhost['host'], user=self.localhost['user'], password=self.localhost['password'], database=self.localhost['database'])
self.cursor = self.connection.cursor()
elif env == 'dev':
self.connection = pymysql.connect(host=self.dev['host'], user=self.dev['user'], password=self.dev['password'],database=self.dev['database'])
self.cursor = self.connection.cursor()
def __del__(self):
print("销毁方法调用.....")
self.connection.close()
self.cursor.close()
# 更新,参数类型是元组
def update(self, sql, params):
try:
self.cursor.execute(sql, params)
self.connection.commit()
return self.cursor.rowcount
except Exception as e:
self.connection.rollback()
print(e)
return 0
# 批量插入,params_list类型是列表,里面数据是元组[(), (), ()]
def insetMany(self, sql, params_list):
try:
self.cursor.executemany(sql, params_list)
self.connection.commit()
return self.cursor.rowcount
except Exception as e:
self.connection.rollback()
print(e)
return 0
# 查询, condition类型是元组
def select(self, sql, condition=None):
self.cursor.execute(sql, condition)
return self.cursor.fetchall()