What happens if I overwrite the pyodbc connection?

Viewed 86

I have some function to execute queries in my database and in that functions I have pyodbc.connect().

What happens if I don't close this connection and call other function that have pyodbc.connect() again? It will ignore the function because the connection is already open?

If it works the way i'm thinking, I want to do it to prevent the connection open and close everytime a function is called

Ps: I know it is not the better way to do it, I want to know only if it works how I'm thinking

1 Answers

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

No:

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')]
Related