所以,我正在为mysql而苦苦挣扎我试着使用mysql.connector
,但当我通过sshtunnel
连接时,它并不愿意合作,所以我转而使用pymysql
,这是我能写的最基本的代码:
import pymysql
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(('192.168.0.x', 22), ssh_username='pi', ssh_password='*********', remote_bind_address=('localhost', 3306)) as tunnel:
tunnel.start()
mydb = pymysql.connect(host="localhost",
user='Mashu',
passwd='******',
port=tunnel.local_bind_port,
db='Special_Channels')
print(mydb)
query = "SELECT * FROM Daily"
cur = mydb.cursor()
data = cur.execute(query)
print(data)
虽然在cur = mydb.cursor()
上,它会引发一个错误:
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
同样在更高的层次上,它是:
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query ([WinError 10053] An established connection was aborted by the software in your host machine)')
我确信数据库和表是存在的,并且这个mysql帐户是可以访问的,因为我已经在其他软件中打开它并对其进行了更改(如果有人想知道的话是DataGrip)。
发布于 2021-09-17 23:25:14
我建议你用mariadb代替pymysql。
pip install mariadb
发布于 2021-09-18 09:31:25
解决方案非常简单。它应该都在with
语句内部,因为隧道连接(因此数据库访问)是在语句外部关闭的,所以它应该看起来像这样:
import pymysql
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(('192.168.0.x', 22), ssh_username='pi', ssh_password='*********', remote_bind_address=('localhost', 3306)) as tunnel:
tunnel.start()
mydb = pymysql.connect(host="localhost",
user='Mashu',
passwd='******',
port=tunnel.local_bind_port,
db='Special_Channels')
print(mydb)
query = "SELECT * FROM Daily"
cur = mydb.cursor()
data = cur.execute(query)
print(data)
https://stackoverflow.com/questions/69230126
复制相似问题