import pymysql
class Database():
def __init__(self, **config):
try:
self.__conn = pymysql.connect(**config)
self.__cursor = self.__conn.cursor()
except Exception as e:
print("数据库连接失败:\n", e)
def select_one(self, table_name, factor_str='', field="*"):
if factor_str == '':
sql = f"select {field} from {table_name}"
else:
sql = f"select {field} from {table_name} where {factor_str}"
self.__cursor.execute(sql)
return self.__cursor.fetchone()
def select_many(self, num, table_name, factor_str='', field="*"):
if factor_str == '':
sql = f"select {field} from {table_name}"
else:
sql = f"select {field} from {table_name} where {factor_str}"
self.__cursor.execute(sql)
return self.__cursor.fetchmany(num)
def select_all(self, table_name, factor_str='', field="*"):
if factor_str == '':
sql = f"select {field} from {table_name}"
else:
sql = f"select {field} from {table_name} where {factor_str}"
self.__cursor.execute(sql)
return self.__cursor.fetchall()
def insert(self,table_name, value):
sql = f"insert into {table_name} values {value}"
try:
self.__cursor.execute(sql)
self.__conn.commit()
print("插入成功")
except Exception as e:
print("插入失败\n", e)
self.__conn.rollback()
def update(self, table_name, val_obl,change_str):
sql = f"update {table_name} set"
for key, val in val_obl.items():
sql += f" {key} = {val},"
sql = sql[:-1]+" where "+change_str
try:
self.__cursor.execute(sql)
self.__conn.commit()
return "修改成功"
except Exception as e:
self.__conn.rollback()
return "修改失败: %s" % e
def delete(self,table_name, item):
sql = f"delete from {table_name} where {item}"
try:
self.__cursor.execute(sql)
self.__conn.commit()
print("删除成功")
except Exception as e:
print("删除失败\n", e)
self.__conn.rollback()