Blog Post

Azure Database Support Blog
1 MIN READ

Lesson Learned #355: Testing the connection latency from Python to Azure SQL Database

Jose_Manuel_Jurado's avatar
May 24, 2023

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!

Published May 24, 2023
Version 1.0
No CommentsBe the first to comment