29 lines
1.0 KiB
Python
29 lines
1.0 KiB
Python
import logging
|
|
import mysql.connector
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def connetti_db(cfg):
|
|
"""
|
|
Establishes a connection to a MySQL database.
|
|
|
|
Args:
|
|
cfg: A configuration object containing database connection parameters.
|
|
It should have the following attributes:
|
|
- dbuser: The database username.
|
|
- dbpass: The database password.
|
|
- dbhost: The database host address.
|
|
- dbport: The database port number.
|
|
- dbname: The name of the database to connect to.
|
|
|
|
Returns:
|
|
A MySQL connection object if the connection is successful, otherwise None.
|
|
"""
|
|
try:
|
|
conn = mysql.connector.connect(user=cfg.dbuser, password=cfg.dbpass, host=cfg.dbhost, port=cfg.dbport, database=cfg.dbname)
|
|
conn.autocommit = True
|
|
logger.info("Connected")
|
|
return conn
|
|
except mysql.connector.Error as e:
|
|
logger.error(f"Database connection error: {e}")
|
|
raise # Re-raise the exception to be handled by the caller |