Lesson Learned #355: Testing the connection latency from Python to Azure SQL Database
Published May 24 2023 07:44 PM 1,438 Views

In some situations, we need to test the connectivity latency using Python. Here you could find a small script about how to do it. 

 

 

import pyodbc
import time

def ConnectToTheDB():
    try:
        print('Connecting to the DB')
        start_time = time.time()    
        conn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};server=tcp:servername.database.windows.net,1433;UID=username;PWD=password;database=DBName;APP=Testing Connection;timeout=30;MARS_Connection=no");  
        print("Connected to the Database %s seconds ---" % ((time.time() - start_time)) )
        return conn
    except BaseException as e:
        print("An error occurred connecting to the DB - " + format(e))
        return 


SQL = "select 1"
nLoop=1
while  nLoop<1000:
    nLoop=nLoop+1
    conn = ConnectToTheDB()
    cursor = conn.cursor()
    start_time = time.time()    
    cursor.execute(SQL)
    row = cursor.fetchone() 
    print("---------------- Loop:%d - %s seconds ---" % (nLoop,(time.time() - start_time)) )
    conn.close()

 

 

 Please, review several considerations about ODBC connection:

 

 

Enjoy!

Version history
Last update:
‎May 24 2023 12:44 PM
Updated by: