简体   繁体   English

启用 Python 通过 SSH 连接到 MySQL

[英]Enable Python to Connect to MySQL via SSH

I'm using pymysql with Python 3.8 to allow Python to make connections to another MySQL server.我在 Python 3.8 中使用 pymysql 以允许 Python 连接到另一个 MySQL 服务器。 I get an error:我收到一个错误:

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

python: Python:

    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')

How to properly connect to MySQL?如何正确连接到MySQL?

When you use a with block in python, the object in the with statement gets its enter method called, the block inside the with runs, and then the exit gets called (optionally with exception info if one was raised).当您在 python 中使用 with 块时,with 语句中的对象会调用其enter方法,运行 with 中的块,然后调用退出(如果引发了异常信息,则可选)。 Thus, if you don't have an enter defined on your class, you'll see this error.因此,如果您没有在类上定义输入,您将看到此错误。

or else instead of above statement you use :否则,您使用的不是上述语句:

connection = pymysql.connect('127.0.0.1', user = '123', password = '123', port = server.local_bind_port)连接 = pymysql.connect('127.0.0.1', 用户 = '123', 密码 = '123', 端口 = server.local_bind_port)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM