You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python的mysql.connector(8.1.0)建立跨服务器双连接时遭遇字符集不兼容问题的求助及解决记录

使用Python的mysql.connector(8.1.0)建立跨服务器双连接时遭遇字符集不兼容问题的求助及解决记录

最近我在使用Python的mysql.connector(版本8.1.0)连接两台不同的MySQL服务器时遇到了一个奇怪的问题,跟大家分享下我的踩坑和解决过程:

问题描述

我编写了一段依次连接两台服务器的代码,先建立并关闭host1上库A的连接,再尝试建立host2上库B的连接,代码如下:

from mysql.connector import MySQLConnection

if __name__ in '__main__':
    # 连接第一台服务器
    try:
        c1 = MySQLConnection(
            host='host1',
            user='*',
            password='*',
            database='A'
        )
        c1.close()
    except Exception as e:
        print(e)
    finally:
        print('c1')

    # 连接第二台服务器
    try:
        c2 = MySQLConnection(
            host='host2',
            user='*',
            password='*',
            database='B'
        )
        c2.close()
    except Exception as e:
        print(e)
    finally:
        print('c2')

运行这段代码时,第二台服务器的连接抛出了错误:Character set 'utf8' unsupported for c2。但如果单独运行连接host2的代码部分,却完全正常,看起来像是第一个连接修改了某个全局配置,影响了后续的连接操作。

问题排查与解决

折腾了一阵后,我终于找到了问题的根源:mysql.connector.constants.CharacterSet中的desc是一个类变量,它会在第一次初始化连接时被全局修改,导致后续连接使用了被改变的字符集配置,从而引发兼容问题。

针对这个问题,我采取了“先备份、后恢复”的思路:在建立第一个连接前,先备份CharacterSet.desc的原始配置,第一个连接完成后再恢复这个配置,这样第二个连接就能使用正常的字符集设置了。修改后的代码如下:

from mysql.connector import MySQLConnection as MySQLConnection
from mysql.connector.constants import CharacterSet

if __name__ in '__main__':
    # 提前备份CharacterSet的desc配置
    desc = CharacterSet.desc.copy()
    
    try:
        c1 = MySQLConnection(
            host='host1',
            user='*',
            password='*',
            database='A'
        )
        c1.close()
    except Exception as e:
        print(e)
    finally:
        print('c1')
    
    # 恢复之前备份的desc配置
    CharacterSet.desc = desc

    try:
        c2 = MySQLConnection(
            host='host2',
            user='*',
            password='*',
            database='B'
        )
        c2.close()
    except Exception as e:
        print(e)
    finally:
        print('c2')

修改后再次运行代码,两个连接都能成功建立并关闭,问题完美解决!

备注:内容来源于stack exchange,提问作者yotheguitou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 13:50:30