import pymysql
class DatabaseHandler:
def __init__(self):
self.db = pymysql.connect(host='127.0.0.1', user='root', db='test')
# 创建游标对象
self.cursor = self.db.cursor()
# def __del__(self):
# self.close()
def close(self):
self.cursor.close()
self.db.close()
def delete_data(self, table_name: str, condition: dict) -> int:
where_clause = " AND ".join(f"`{key}`='{value}'" for key, value in condition.items())
sql = f"DELETE FROM `{table_name}` WHERE {where_clause};"
affected_rows = self.cursor.execute(sql)
self.db.commit()
return affected_rows
def select_data(self, table_name: str, columns: list = None, condition: dict = None, limit: int = None) -> list:
if not columns:
select_clause = "*"
else:
select_clause = ", ".join(f"`{column}`" for column in columns)
where_clause = ""
if condition:
where_clause = " AND ".join(f"`{key}`='{value}'" for key, value in condition.items())
where_clause = f"WHERE {where_clause}"
limit_clause = ""
if limit:
limit_clause = f"LIMIT {limit}"
sql = f"SELECT {select_clause} FROM `{table_name}` {where_clause} {limit_clause};"
self.cursor.execute(sql)
rows = self.cursor.fetchall()
return rows
def insert_data_by_array(self, info: dict, table_name: str) -> int:
keys = ", ".join(f"`{key}`" for key in info.keys())
values = ", ".join(f"'{value}'" for value in info.values())
sql = f"INSERT INTO `{table_name}`({keys}) VALUES ({values});"
self.cursor.execute(sql)
self.db.commit()
last_inserted_id = self.cursor.lastrowid
return last_inserted_id
def update_data(self, info: dict, table_name: str, condition: dict) -> int:
set_clause = ", ".join(f"`{key}`='{value}'" for key, value in info.items())
where_clause = " AND ".join(f"`{key}`='{value}'" for key, value in condition.items())
sql = f"UPDATE `{table_name}` SET {set_clause} WHERE {where_clause};"
affected_rows = self.cursor.execute(sql)
self.db.commit()
return affected_rows
标签:Python,clause,数据库,value,cursor,so,key,where,self
From: https://blog.51cto.com/u_14523369/6183210