问题
I'm trying to use the MySQL connector in Python, through an SSHTunnel, and I'm getting a MySQL Connection not available. error.
It seems to be talking to the server (I get an access denied message if I change the password), but it fails when I try to create a cursor object (specifically, when the MySQL library runs CMySQLConnection.is_connected()
.
I can connect to the database by SSHing in using the same credentials, then running mysql
in the command line.
Code:
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()
I get this stacktrace:
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.
Potentially relevant links:
- https://www.pythonanywhere.com/forums/topic/3945/
来源:https://stackoverflow.com/questions/58919186/sshtunnel-and-mysql-connector-in-python-failing