data.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import mysql.connector
  2. class MySQLTool:
  3. def __init__(self, host, user, password, database):
  4. self.host = host
  5. self.user = user
  6. self.password = password
  7. self.database = database
  8. self.connection = None
  9. self.cursor = None
  10. def connect(self):
  11. self.connection = mysql.connector.connect(
  12. host=self.host,
  13. user=self.user,
  14. password=self.password,
  15. database=self.database
  16. )
  17. self.cursor = self.connection.cursor()
  18. def disconnect(self):
  19. if self.cursor:
  20. self.cursor.close()
  21. if self.connection:
  22. self.connection.close()
  23. def select(self, table, columns='*', conditions=None):
  24. query = f"SELECT {columns} FROM {table}"
  25. if conditions:
  26. query += " WHERE " + " AND ".join([f"{key} = %s" for key in conditions.keys()])
  27. values = tuple(conditions.values())
  28. self.cursor.execute(query, values)
  29. else:
  30. self.cursor.execute(query)
  31. result = self.cursor.fetchall()
  32. return result
  33. def insert(self, table, columns, values):
  34. query = f"INSERT INTO {table} ({', '.join(columns)}) VALUES ({', '.join(['%s' for _ in columns])})"
  35. self.cursor.execute(query, values)
  36. self.connection.commit()
  37. affected_rows = self.cursor.rowcount
  38. return affected_rows
  39. def update(self, table, set_values, conditions=None):
  40. query = f"UPDATE {table} SET " + ", ".join([f"{key} = %s" for key in set_values.keys()])
  41. values = tuple(set_values.values())
  42. if conditions:
  43. query += " WHERE " + " AND ".join([f"{key} = %s" for key in conditions.keys()])
  44. values += tuple(conditions.values())
  45. self.cursor.execute(query, values)
  46. self.connection.commit()
  47. affected_rows = self.cursor.rowcount
  48. return affected_rows
  49. def delete(self, table, conditions=None):
  50. query = f"DELETE FROM {table}"
  51. if conditions:
  52. query += " WHERE " + " AND ".join([f"{key} = %s" for key in conditions.keys()])
  53. values = tuple(conditions.values())
  54. self.cursor.execute(query, values)
  55. else:
  56. self.cursor.execute(query)
  57. self.connection.commit()
  58. affected_rows = self.cursor.rowcount
  59. return affected_rows