Python MySQL - 从函数返回光标和连接

时间:2017-09-18 07:30:53

标签: python mysql

以前我总是使用像...这样的东西。

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

1 个答案:

答案 0 :(得分:2)

Python在__exit__执行后调用特殊方法with..as,因此在从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