Python mysql(使用pymysql)无法连接

时间:2017-03-20 15:01:26

标签: python mysql pymysql

我使用Python Pymysql连接到AWS RDS db。 这一天都在运行,但现在我无法连接到数据库。 但是,当我使用相同的机器和相同的凭据时,它通过Mysql工作台连接,但通过pycharm这不起作用。,

代码:

   configParser = ConfigParser.RawConfigParser()
   configFilePath = r'docs/credentials.cfg'
   configParser.read(configFilePath)

   User = configParser.get('aws-config','user')
   Pswd = configParser.get('aws-config','pswd')
   Host = configParser.get('aws-config','hostdps')
   Databs = configParser.get('aws-config','databs')
   db = pymysql.connect(host=Host, user=User, password=Pswd, db=Databs, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor,local_infile=True)

错误:

  File "/usr/local/lib/python2.7/dist-packages/pymysql/__init__.py", line 90, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 688, in __init__
    self.connect()
  File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 906, in connect
    self._request_authentication()
  File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 1114, in _request_authentication
    auth_packet = self._read_packet()
  File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 961, in _read_packet
    packet_header = self._read_bytes(4)
  File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 995, in _read_bytes
    "Lost connection to MySQL server during query (%s)" % (e,))
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query ([Errno 104] Connection reset by peer)')

如何确保在生产中不会发生这种情况? (将来防止此类失败)。

1 个答案:

答案 0 :(得分:-1)

为什么你不使用连接池?
连接池可以自动管理连接,因此可以解决此问题。

你可以试试任何python mysql池。
池例子
这个this link 或者直接使用github方便的代码。PyMysqlPool