Home:ALL Converter>Implement connection pooling with Python for connecting to SQL Server on Windows

Implement connection pooling with Python for connecting to SQL Server on Windows

Ask Time:2021-09-02T22:10:12         Author:gtrosh.ka

Json Formatter

I am writing a Python script that will read data from a SQL Server database. For this I have used pyodbc to connect to SQL Server on Windows (my driver is ODBC Driver 17 for SQL Server).

My script works fine, but I need to use a connection pool instead of a single connection to manage resources more effectively. However the documentation for pyodbc only mentions pooling without providing examples of how connection pooling can be implemented. Any ideas of how this can be done using Python while connecting to an SQL Server? I only found solutions for PostgreSQL that use psycopg2, but this does not work for me obviously.

At the moment my code looks like this (please disregard the missing indentation which happened when copying the file from my IDE):

def get_limited_rows(size):
try:
    server = 'here-is-IP-address-of-servier'
    database = 'here-is-my-db-name'
    username = 'here-is-my-username'
    password = 'here-is-my-password'
    conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password)
    cursor = conn.cursor()
    print('Connected to database')

    select_query = 'select APPN, APPD from MAIN'
    cursor.execute(select_query)
    while True:
        records = cursor.fetchmany(size)
        if not records:
            cursor.close()
            sys.exit("Completed")
        else: 
            for record in records:
                print(record)
            time.sleep(10)
except pyodbc.Error as error:
    print('Error reading data from table', error)
finally:
    if (conn):
        conn.close()
        print('Data base connection closed')

Author:gtrosh.ka,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69031942/implement-connection-pooling-with-python-for-connecting-to-sql-server-on-windows
yy