我正在尝试通过SSHTunnel在Python中使用MySQL连接器,但出现 MySQL连接不可用。错误。
它似乎正在与服务器通信(如果更改密码,我会收到拒绝访问的消息),但是当我尝试创建游标对象时(特别是当MySQL库运行CMySQLConnection.is_connected()
时,它失败了。
我可以使用相同的凭据通过SSH进入数据库,然后在命令行中运行mysql
。
代码:
with sshtunnel.SSHTunnelForwarder(
('vpn.example.com',22),ssh_username='ssh_username',ssh_pkey='~/.ssh/key.pem',remote_bind_address=(
'db.example.com',3306
),) as tunnel:
try:
backup_cnx = mysql.connector.connect(
user='vpn_username',password='bts5eva',host='127.0.0.1',port=tunnel.local_bind_port,database='pretend_db_name',# connection_timeout=5
)
cursor = backup_cnx.cursor()
day_after = day + datetime.timedelta(days=1)
cursor.execute(
"SELECT * "
" FROM mah_table "
" WHERE timestamp < {day_after} AND timestamp > {day}"
" ORDER BY timestamp".format(
day=day.strftime("%Y-%m-%d"),day_after=day_after.strftime("%Y-%m-%d")
)
)
results = cursor.fetchall()
finally:
backup_cnx.close()
我得到了这个堆栈跟踪:
Traceback (most recent call last):
File "code/restore_missing_directives.py",line 41,in <module>
cursor = backup_cnx.cursor()
File "code/env/lib/python2.7/site-packages/mysql/connector/connection_cext.py",line 524,in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
可能相关的链接: