"""
@File : my_mysql.py
@Time : 2022/9/3 17:32
"""
import pymysql
class MySql:
def __init__(self, operate_tablename:str,my_sqldb_config_param:dict):
assert isinstance(my_sqldb_config_param,dict),"请以字典类型的格式传入!"
self._operate_tablename = operate_tablename
try:
self._conn = pymysql.connect(**my_sqldb_config_param)
self._cursor = self._conn.cursor()
self._get_field()
except Exception as e:
raise Exception(f"数据库连接失败!!!\n请检查表名、配置参数是否正确或检查本地数据库是否已启动!\n{e}")
@property
def get_connect(self):
return self._conn
@property
def get_cursor(self):
return self._cursor
@property
def get_description(self):
return self._desc
@property
def operate_tablename(self):
return f"正在操作 {self._operate_tablename}表!!!"
@operate_tablename.setter
def operate_tablename(self,operate_tablename):
assert operate_tablename !="", "请输入要操作的表名!"
print(f"{self._operate_tablename} 表已被更换!")
self._operate_tablename = operate_tablename
self._get_field()
def _get_field(self):
self._cursor.execute(f"select * from {self._operate_tablename}")
self._desc = self._cursor.description
self._field_ = []
for field in self._desc:
self._field_.append(field[0])
def _sql(self,sql,msg=""):
try:
self._cursor.execute(sql)
self._conn.commit()
if msg:print(f"数据{msg}成功!")
return True
except Exception as e:
if msg:print(f"\033[31m数据{msg}失败!!!\n{e} \033[0m")
self._conn.rollback()
return False
def insert(self, *value):
if not isinstance(value[0],tuple): raise Exception("要求传入的参数类型为tuple元组!!!")
if len(value) == 1: value=value[0]
else:value = str(value)[1:-1]
sql = f"insert into {self._operate_tablename}({','.join(self._field_[1:])}) values {value}"
if not self._sql(sql,f"{value}插入"):
print("\n\033[31m:请检查每一条记录字段是否正确!!!\033[0m\n")
def insert_by_sql(self, sql):
self._sql(sql,"插入")
def delete_by_id(self,id_:int):
sql = f"delete from {self._operate_tablename} where id = {id_}"
if self._sql(sql):print(f"id={id_}记录,删除成功!")
else:print(f"\n\033[31m:id = {id_}记录,删除失败!!!\033[0m\n")
def delete_by_sql(self, sql):
self._sql(sql,"删除")
def update_by_id(self, id_:int, set_field:dict):
assert isinstance(set_field,dict),"请以字典类型的格式传入!"
tempset_field = []
for i in set_field:
tempset_field.append(f"{i}='{set_field[i]}'")
set_field = ",".join(tempset_field)
sql = f"update {self._operate_tablename} set {set_field} where id = {id_}"
if self._sql(sql):print(f"id={id_}记录,{set_field}修改成功!")
else:print(f"\n\033[31m:id = {id_}记录,{set_field}修改失败!!!\033[0m\n")
def update_by_sql(self, sql):
self._sql(sql,"修改")
def select_by_id(self,id_:int,field="*"):
if field != "*": field = ','.join(field)
sql = f"select {field} from {self._operate_tablename} where id={id_}"
self._cursor.execute(sql)
return self._cursor.fetchone()
def select_many(self,num:int,query_builder=None,field="*"):
if field != "*": field = ','.join(field)
sql = f"select {field} from {self._operate_tablename}"
if query_builder:
if isinstance(query_builder,dict) and len(query_builder) == 1:
query_builder = list(query_builder.items())[0]
sql = f"select {field} from {self._operate_tablename} where {query_builder[0]}='{query_builder[1]}'"
else: raise Exception("要求输入的条件为dict(字典)类型并且只能有一对键值(:len(dict)=1)!!!")
self._cursor.execute(sql)
return self._cursor.fetchmany(num)
def select_all(self, field="*"):
if field != "*": field = ','.join(field)
sql = f"select {field} from {self._operate_tablename}"
self._cursor.execute(sql)
return self._cursor.fetchall()
def select_by_sql(self, sql):
try:
self._cursor.execute(sql)
return self._cursor.fetchall()
except Exception as e:
print(f"\033[31m:数据查询失败!!!\n{e} \033[0m")
def __del__(self):
self._cursor.close()
self._conn.close()
def my_mysql_test(operate_tablename:str, my_sqldb_config_param:dict):
print("-------------my_mysql_test:注意下面传入数据的格式---------------")
mysql = MySql(operate_tablename=operate_tablename, my_sqldb_config_param=my_sqldb_config_param)
print(mysql.operate_tablename)
mysql.operate_tablename = "tb_user"
print(mysql.operate_tablename)
print("----------------insert-----------------")
mysql.insert_by_sql('insert into tb_user(name,age,gender) values ("111", 12, "男"), ("222", 22, "女"),("333", 32, "女")')
mysql.insert(("444", 42, "男"))
mysql.insert(("555",52,"男"),("666",62,"女"))
mysql.insert(("999", 92, "男"), ("000", '28', "女", "xxx"))
print("----------------select-----------------")
result = mysql.select_by_sql("select * from tb_user where gender='男'")
print("查询:自定义sql查询数据:\n", result)
result = mysql.select_all()
print("查询:表中所有数据:\n", result)
result = mysql.select_by_id(1)
print("\n查询:通过id:", result)
result = mysql.select_many(1, {"gender": "女"})
print('查询:指定查询多少条数数据,可根据简单条件查询(where 字段=”“):', result)
print("----------------delete-----------------")
mysql.delete_by_sql('delete from tb_user where gender="男"')
mysql.delete_by_id(4)
result = mysql.select_all()
print("删除数据后查询表中所有数据:\n", result)
print("----------------update-----------------")
mysql.update_by_sql("update tb_user set name='update_name',gender='男' where id = 6")
mysql.update_by_id(3, {"age": "180"})
mysql.update_by_id(2, {"name": "update_name", "age": "999"})
mysql.update_by_id(6, {"xxx": "updateName", "yyy": "18"})
result = mysql.select_all()
print("更新数据后查询表中所有数据:\n", result)
if __name__ == '__main__':
my_sqldb_config_param = {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password": "***",
"database": "pythondemo",
"charset": "utf8"
}
operate_tablename = "tb_test"
my_mysql_test(operate_tablename,my_sqldb_config_param)