所以我正在努力让
mysql-connector-python
与 sshtunnel
合作
with SSHTunnelForwarder(('192.168.0.1', 22), ssh_username='pi', ssh_password='*********', remote_bind_address=('localhost', 3306)) as tunnel:
tunnel.start()
mydb = mysql.connector.connect(host="localhost",
user='Mashu',
password='*******',
port=tunnel.local_bind_port,
db='mysql')
print(mydb)
cur = mydb.cursor()
cur.execute('USE mysql')
print(cur.execute('SELECT * FROM user'))
它似乎执行得很顺利,但是当我想创建光标时它说
mysql.connector.errors.OperationalError: MySQL Connection not available.
我进一步调查,发现值连接到本地绑定,所以
local_bind_address
,local_bind_host
等都设置为错误,说:
Server is not started. Please .start() first!
即使我的代码中有
tunnel.start()
您正在使用带有
with SSHTunnelForwarder
的上下文管理器,这意味着它将在退出范围时关闭连接。将 cur = mydb.cursor
放入上下文管理器范围内将解决该问题。
或者,您可以删除上下文管理器,但请记住关闭隧道,因为您是明确启动它的。
tunnel = get_ssh_tunnel(host, int(port), ssh_config)
tunnel.start()
conn = #connection settings
# do stuff
tunnel.close()
conn.close()