【问题标题】:Python MySQL - Returning Cursor and Connection from FunctionPython MySQL - 从函数返回游标和连接
【发布时间】: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

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    Python 在with..as 执行后调用特殊方法__exit__,因此您的连接在从with 的上下文返回后关闭。将隧道 forvarder 分配给如下变量,您将能够在函数范围之外使用连接

    tunnel = SSHTunnelForwarder(
            (ssh_host, ssh_port),
            ssh_username=ssh_user,
            ssh_pkey=mypkey,
            remote_bind_address=(sql_hostname, sql_port))
    

    阅读更多关于化合物with 声明in the docs

    【讨论】:

    • 是的 - 效果很好。将阅读with 以及有关打开和关闭 SSH 隧道的良好做法。
    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多