'Python mysql-connector hangs indefinitely when connecting to remote mysql via SSH

I am Testing out connection to mysql server with python. I need to ssh into the server and establish a mysql connection. The following code works:

from sshtunnel import SSHTunnelForwarder
import pymysql
import mysql.connector
    
with SSHTunnelForwarder((ssh_host, 22), ssh_username=ssh_user, ssh_password=ssh_password,
            remote_bind_address=("127.0.0.1", 3306)) as tunnel:

    config = {
                    'user': user,
                    'password': password,
                    'host': tunnel.local_bind_host,
                    'port': tunnel.local_bind_port,
                    'database': db
                }
    
    conn = pymysql.connect(**config)
    query = '''SELECT VERSION();'''
    data = pd.read_sql_query(query, conn)
    print(data)
    connection.close()

However, when using mysql.connector instead of pymysql such as below:

with SSHTunnelForwarder((ssh_host, 22), ssh_username=ssh_user, ssh_password=ssh_password,
                remote_bind_address=("127.0.0.1", 3306)) as tunnel:

        config = {
                        'user': user,
                        'password': password,
                        'host': tunnel.local_bind_host,
                        'port': tunnel.local_bind_port,
                        'database': db
                    }
        
        conn = mysql.connector.connect(**config)
        mycursor = cnx.cursor()
        mycursor.execute("SELECT VERSION()")
        myresult = mycursor.fetchall()

The code stops at conn = mysql.connector.connect(**config). It never gives an error or stops, it just hangs on this line.

Why is this?

Aren't the config attributes valid for this module?



Solution 1:[1]

As there seems to be an aswer here I followed the comment from @André Restivo and it seems to work for me, set use_pure to True. I'm not sure what does this exactly do:

    def __get_db_connection(self) -> None:
        """
        Connect to the database
        """
        try:
            logger.debug(f'Connecting to mysql db "{self.config.mysql_database}"...')
            with mysql.connector.connect(
                host=self.config.mysql_ip,
                port=self.tunnel.local_bind_port,
                user=self.config.mysql_user,
                password=self.config.mysql_password,
                database=self.config.mysql_database,
                use_pure=True
            ) as connection:
                self.connection = connection
                logger.info(connection)
        except mysql.connector as e:
            logger.error(e)
            raise

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nck