【问题标题】:Enable Python to Connect to MySQL via SSH启用 Python 通过 SSH 连接到 MySQL
【发布时间】:2020-09-18 16:38:08
【问题描述】:

我在 Python 3.8 中使用 pymysql 以允许 Python 连接到另一个 MySQL 服务器。我收到一个错误:

with pymysql.connect('127.0.0.1', user = '123', password = '123', port = server.local_bind_port) as connection:
AttributeError: __enter__

蟒蛇:

    from sshtunnel import SSHTunnelForwarder
    import pymysql
    
    
    with SSHTunnelForwarder(
        ('76.21.187.192', 2222),
        ssh_username = '123', 
        ssh_password = '123',
        remote_bind_address = ('127.0.0.1', 3306)) as server: 
    
        with pymysql.connect('127.0.0.1', user = '123', password = '123', port = server.local_bind_port) as connection:
            print('OK')

如何正确连接MySQL?

【问题讨论】:

    标签: python mysql ssh


    【解决方案1】:

    当你在 python 中使用 with 块时,with 语句中的对象会调用它的 enter 方法,with 内的块会运行,然后 exit 会被调用调用(如果提出了异常信息,则可以选择使用异常信息)。因此,如果您没有在类中定义 enter,您将看到此错误。

    或者你使用上面的语句来代替:

    connection = pymysql.connect('127.0.0.1', user = '123', password = '123', port = server.local_bind_port)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 2020-10-10
      • 2018-04-05
      • 2021-08-07
      • 2014-03-21
      相关资源
      最近更新 更多