mysql.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import mysql.connector
  2. from flask import current_app
  3. def execute_query(query, params=None, fetch_one=False):
  4. """Execute a SQL query and optionally fetch results."""
  5. try:
  6. # Get database configuration from the current app context
  7. db_config = {
  8. "host": current_app.config['DBHOST'],
  9. "user": current_app.config['DBUSER'],
  10. "password": current_app.config['DBPASS'],
  11. "database": current_app.config['DATABASE'],
  12. }
  13. # Establish database connection
  14. connection = mysql.connector.connect(**db_config)
  15. cursor = connection.cursor(dictionary=True)
  16. # Execute the query with optional parameters
  17. cursor.execute(query, params)
  18. # Fetch results if it's a SELECT query
  19. if query.strip().upper().startswith("SELECT"):
  20. result = cursor.fetchone() if fetch_one else cursor.fetchall()
  21. else:
  22. # Commit changes for INSERT, UPDATE, DELETE
  23. connection.commit()
  24. result = cursor.rowcount # Number of affected rows
  25. # Close the database connection
  26. cursor.close()
  27. connection.close()
  28. return result
  29. except mysql.connector.Error as err:
  30. print("Error: ", err)
  31. return None