通过Python连接到MySQL,结果矛盾

时间:2019-03-18 12:46:56

标签: mysql pythonanywhere ssh-tunnel

我正在尝试连接到Python Anywhere上托管的MySQL数据库。在下面的示例中,connection.get_server_info()返回结果,但是connection.is_connected()返回False,但我不确定为什么。

这是我的代码:

import mysql.connector
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='USERNAME', ssh_password='PASSWORD',
    remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    connection = mysql.connector.connect(
        user='USERNAME', password='DB_PASSWORD',
        host='127.0.0.1', port=tunnel.local_bind_port,
        database='USERNAME$default',
    )
db_info = connection.get_server_info()
if connection.is_connected():      
    print('Connected to MySQL DB...version on ', db_info)
else:
    print('Failed to connect.')
print(db_info)
connection.close()

我在Python Anywhere上有一个付费帐户,因此应该可以进行SSH隧道

1 个答案:

答案 0 :(得分:1)

这是因为您要在SSH隧道关闭后尝试访问它;当退出with块时,隧道是关闭的,因此使用该连接的所有内容都需要缩进,以便包含在其中。您上面的代码如下:

import mysql.connector
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='USERNAME', ssh_password='PASSWORD',
    remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    connection = mysql.connector.connect(
        user='USERNAME', password='DB_PASSWORD',
        host='127.0.0.1', port=tunnel.local_bind_port,
        database='USERNAME$default',
    )
    db_info = connection.get_server_info()
    if connection.is_connected():      
        print('Connected to MySQL DB...version on ', db_info)
    else:
        print('Failed to connect.')
    print(db_info)
    connection.close()