You will need to follow the steps below before connecting to Azure SQL Server using Python.
pyodbc
by running the command:pip install pyodbc
Now, we are ready to connect to SQL Server using Python. Take a look at the code below.
import pyodbc server = 'tcp:myserver.database.windows.net' database = 'mydb' username = 'myusername' password = 'mypassword' driver = '{ODBC Driver 17 for SQL Server}' try: cnxn = pyodbc.connect('DRIVER=' + driver + ';SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password) cursor = cnxn.cursor() print('Connection established') except: print('Cannot connect to SQL server')
Explanation:
connect()
method and pass all the parameters that we have defined in the above steps.Use
try-except
blocks to avoid any program crashes.
RELATED TAGS
CONTRIBUTOR
View all Courses