3

I am using mysql.connector for Python. Below are my connection parameters. How can I set a timeout or increase the default timeout?

class Config(object):
    """Configure me so examples work

    Use me like this:

        mysql.connector.Connect(**Config.dbinfo())
    """

    HOST = dbhost
    DATABASE = dbdatabase
    USER = dbusername
    PASSWORD = dbpassword
    PORT = 3306

    CHARSET = 'utf8'
    UNICODE = True
    WARNINGS = True

    @classmethod
    def dbinfo(cls):
        return {
            'host': cls.HOST,
            'port': cls.PORT,
            'database': cls.DATABASE,
            'user': cls.USER,
            'password': cls.PASSWORD,
            'charset': cls.CHARSET,
            'use_unicode': cls.UNICODE,
            'get_warnings': cls.WARNINGS,
            }
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
Tampa
  • 75,446
  • 119
  • 278
  • 425

4 Answers4

5

According to MySQL Connector/Python :: 6 Connector/Python Connection Arguments in the official documentation:

To set a timeout value for connections, use connection_timeout.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • 2
    The Python documentation doesn't specify. The [MySQL documentation](https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_connect_timeout) specifies "seconds", so I'd _guess_ the same, but would measure myself to be sure. – johnsyweb Jul 20 '19 at 11:18
2

If you are using mysql.connector.connect to connect with DB you can simply use connection_timeout parameter to define a timeout externally make sure value given will be in seconds instead of milliseconds.

conn = mysql.connector.connect(
    pool_name=pool['name'], 
    pool_size=pool['size'],
    host=config['host'], 
    port=config['port'], 
    user=config['user'],
    passwd=config['passwd'],
    db=config['db'],
    charset=config['charset'], 
    use_unicode=True,
    connection_timeout=10
)
officialrahulmandal
  • 2,473
  • 1
  • 23
  • 31
1

I found something here: http://dev.mysql.com/doc/refman/5.5/en/connector-python-connectargs.html I think you are looking for the parameter connection_timeout (connect_timeout*)

Robert Bean
  • 851
  • 2
  • 11
  • 21
0

This works for me:

conn = mysql.connector.connect(
    pool_name=pool['name'], 
    pool_size=pool['size'],
    host=config['host'], 
    port=config['port'], 
    user=config['user'],
    passwd=config['passwd'],
    db=config['db'],
    charset=config['charset'], 
    use_unicode=True,
    connect_timeout=1000
)

If you use MySQLdb:

conn = MySQLdb.connect(
    host=config['host'], 
    port=config['port'], 
    user=config['user'], 
    passwd=config['passwd'],
    db=config['db'], 
    charset=config['charset'], 
    use_unicode=True,
    connect_timeout=1000
)
SilverNak
  • 3,283
  • 4
  • 28
  • 44
LuciferJack
  • 781
  • 11
  • 12