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

This post has been republished via RSS; it originally appeared at: Microsoft Tech Community - Latest Blogs - .

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!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.