以前我总是使用类似...
def getConn():
cnx = mysql.connector.connect(user='user', password='pass',
host='hostIP',
database='database')
cur = cnx.cursor(buffered=True)
return [cnx, cur]
返回cnx和cur对象以供使用。这很好用。
我现在需要使用 SSH 连接到数据库。
下面的示例在函数内执行查询,但不会返回 cnx 或 cur 对象供以后使用,因此我打印了结果,然后是错误
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
我似乎遇到了与 Why won't Python return my mysql-connector cursor from a function? 相同的问题(尽管返回了不同的错误)
这个问题涉及为什么 - 我想知道是否有解决方案。
def returnConnect():
mypkey = paramiko.RSAKey.from_private_key_file('/Users/me/.ssh/id_rsa')
sql_hostname = '127.0.0.1'
with SSHTunnelForwarder(
(ssh_host, ssh_port),
ssh_username=ssh_user,
ssh_pkey=mypkey,
remote_bind_address=(sql_hostname, sql_port)) as tunnel:
cnx = mysql.connector.connect(host='127.0.0.1', user=sql_username,
passwd=sql_password, db=sql_main_database,
port=tunnel.local_bind_port)
cur = cnx.cursor(buffered=True)
sql = "select * from table"
cur.execute(sql)
result = cur.fetchall()
print result
return [cnx, cur]
conn = returnConnect()
cnx = conn[0]
cur = conn[1]
sql = "select * from table"
cur.execute(sql)
result = cur.fetchall()
cnx.close()
print result
最佳答案
Python 在 with..as
执行后调用特殊方法 __exit__
,因此您的连接在从 with
的上下文返回后关闭。将隧道转发器分配给如下变量,您将能够在函数范围之外使用连接
tunnel = SSHTunnelForwarder(
(ssh_host, ssh_port),
ssh_username=ssh_user,
ssh_pkey=mypkey,
remote_bind_address=(sql_hostname, sql_port))
阅读有关复合 with
语句的更多信息 in the docs .
关于Python MySQL - 从函数返回游标和连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46273873/