Python: pyodbc with SQL Server

(Last Updated On: )

This post is in regards to connecting to SQL Server using pyodbc.

Install package

  1. pip install pyodbc

If you are running in Databricks then the current driver will be “{ODBC Driver 17 for SQL Server}”.

If you are running in Synapse then the current driver will be “{ODBC Driver 18 for SQL Server}”.

Check pyodbc Version

  1. import pyodbc
  2. pyodbc.drivers()

Check Which Version of pyodbc in Databricks

  1. %sh
  2. cat /etc/odbcinst.ini

Install Databricks driver 17

  1. curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
  2. curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
  3. apt-get update
  4. ACCEPT_EULA=Y apt-get install msodbcsql17
  5. apt-get -y install unixodbc-dev

Connect using SQL Auth

I do not recommend SQL Auth

  1. import pyodbc
  2.  
  3. secret = "<GET SECRET SECURELY>"
  4.  
  5. connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};Server=tcp:<SERVER_NAME>;PORT=<PORT>;Database=<DATABASE>;Uid=<USER>;Pwd=<SECRET>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=<TIMEOUT>;')

Connect Using Domain Auth

  1. import pyodbc
  2.  
  3. secret = "<GET SECRET SECURELY>"
  4.  
  5. connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};Server=tcp:<SERVER_NAME>;PORT=<PORT>;Database=<DATABASE>;Uid=<USER>;Pwd=<SECRET>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=<TIMEOUT>;Authentication=ActiveDirectoryPassword')

Connect using Azure SPN

  1. pip install msal
  1. import struct
  2. import msal
  3.  
  4. global_token_cache = msal.TokenCache()
  5. secret = "<GET SECRET SECURELY>"
  6.  
  7. global_spn_app = msal.ConfidentialClientApplication(
  8. <CLIENT_ID>, Authority='https://login.microsoftonline.com/<TENANT_ID>',
  9. client_credential=secret,
  10. token_cache=global_token_cache,
  11. )
  12.  
  13. result = global_spn_app.acquire_token_for_client(scopes=['https://database.windows.net//.default'])
  14. SQL_COPT_SS_ACCESS_TOKEN = 1256
  15.  
  16. token = bytes(result['access_token'], 'utf-8')
  17. exptoken = b"";
  18.  
  19. for i in token:
  20. exptoken += bytes({i});
  21. exptoken += bytes(1);
  22.  
  23. token_struct = struct.pack("=i", len(exptoken)) + exptoken;
  24.  
  25. connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};Server=tcp:<SERVER_NAME>;PORT=<PORT>;Database=<DATABASE>;Uid=<USER>;Pwd=<SECRET>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=<TIMEOUT>;' attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:tokenstruct })

Once you have the connection you can setup the cursor.

  1. cursor = connection.cursor()

Then execute a command

  1. command = "<COMMAND>"
  2. params = ()
  3. cursor.execute(command, params)
  4. connection.commit()

After you Are finish Close

  1. cursor.close()
  2. connection.close()