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

标签 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: 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/

相关文章:

python - 使用 resample/timedelta 进行 pandas 在线日志记录

python - 为什么TCP客户端变慢然后产生OSError : [Errno 99] Cannot assign requested address

python - 如何使用Python3查找日期列表中的所有日期

php - 为什么我用PDO插入非英文字符会变成怪物?

mysql - 为什么这个sql在prepare之后就能执行成功呢?

php - 我如何自动更新连接表并从连接表访问数据?

如果搜索不存在,MySql 使用默认值

python - Windows 无法正确读取 .py 文件

c++ - Boost::Python 中的智能指针转换

php - 选择连接表原则 2 中的列