如果我覆盖 pyodbc 连接会怎样?

What happens if I overwrite the pyodbc connection?

我有一些函数可以在我的数据库中执行查询,在这些函数中我有 pyodbc.connect()。

如果我不关闭此连接并再次调用其他具有 pyodbc.connect() 的函数,会发生什么情况?它会忽略该功能,因为连接已经打开?

如果它按照我的想法工作,我想这样做以防止每次调用函数时打开和关闭连接

Ps:我知道这不是更好的方法,我只想知道它是否像我想的那样有效

It will ignore the function because the connection is already open?

否:

import pyodbc

conn_str = (
    r'DRIVER=ODBC Driver 17 for SQL Server;'
    r'SERVER=(local)\SQLEXPRESS;'
    r'DATABASE=myDb;'
    "Trusted_Connection=yes;"
)


def get_connections(cnxn):
    crsr = cnxn.cursor()
    sql = (
        "SELECT session_id, login_name, status "
        "FROM sys.dm_exec_sessions "
        "WHERE program_name = 'Python' "
    )
    connections = crsr.execute(sql).fetchall()
    return connections


def subroutine():
    cnxn = pyodbc.connect(conn_str)
    return get_connections(cnxn)


cnxn = pyodbc.connect(conn_str)
print(get_connections(cnxn))
# [(56, 'GORD-HP\Gord', 'running')]
print(subroutine())
# [(56, 'GORD-HP\Gord', 'sleeping'), (57, 'GORD-HP\Gord', 'running')]
print(get_connections(cnxn))
# [(56, 'GORD-HP\Gord', 'running')]