【发布时间】:2017-09-18 07:30:53
【问题描述】:
以前我总是使用类似...的东西
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: 在查询期间丢失与 MySQL 服务器的连接
我似乎遇到了同样的问题(尽管返回了不同的错误)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
【问题讨论】: