用于Python的MySQL连接器

时间:2013-01-05 01:29:15

标签: python mysql mysql-connector-python

我正在使用mysql.connector用于Python。以下是我的连接参数。如何设置超时或增加默认超时?

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,
            }

4 个答案:

答案 0 :(得分:3)

根据官方文件中的MySQL Connector/Python :: 6 Connector/Python Connection Arguments

  

要为连接设置超时值,请使用connection_timeout

答案 1 :(得分:1)

我在这里找到了一些东西:http://dev.mysql.com/doc/refman/5.5/en/connector-python-connectargs.html 我想你正在寻找参数          connection_timeout(connect_timeout *)

答案 2 :(得分:1)

如果您使用mysql.connector.connect与数据库连接,则可以简单地使用connection_timeout参数在外部定义超时,以确保给定的值将在seconds中而不是毫秒内。

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
)

答案 3 :(得分:0)

这对我有用:

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
)

如果您使用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
)