Create MySQL connection

    0

    4

    databasemysql
    Python public recipes

    In this snippet, we create a connection to the database. If the database is unavailable, we wait 5 seconds and keep retrying.

    Library: mysql-connector-python

    import mysql.connector
    import logging
    
    def mysql_connection(config):
      host = os.getenv("DATABASE_HOST", host)
      user = os.getenv("DATABASE_USER", user)
      password = os.getenv("DATABASE_PASSWORD", password)
      database = os.getenv("DATABASE_NAME", dbname)
      logging.debug("[DB] Connecting to host %s", host)
    
      while True:
        try:
          connection = mysql.connector.connect(
            host=host,
            user=user,
            passwd=password,
            database=database,
            charset='utf8mb4',
            use_pure=True,
            connection_timeout=5)
          return connection
        except mysql.connector.Error:
          logging.error("Cannot connect to the database")
          time.sleep(5)
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.