Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
azure
communitycreator

How to connect an Azure SQL server using Python

Harsh Jain

Setup the environment

You will need to follow the steps below before connecting to Azure SQL Server using Python.

Connect to SQL server

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')
Connect to Azure SQL server using Python

Explanation:

  • In line 1, we import the required package.
  • In line 3, we define the SQL server URL.
  • In line 4, we specify the SQL Server database name to which we want to connect.
  • In line 5, we define the username for accessing the database.
  • In line 6, we define the password for accessing the database.
  • In line 7, we define the SQL server driver.
  • In line 10, we use the connect() method and pass all the parameters that we have defined in the above steps.
  • In line 16, we get the cursor object if the connection is successful. This cursor object can then be used for performing all the database operations.
  • If there is an error while connecting to the server, in line 19, we can print a message stating that the connection was not established.

    Use try-except blocks to avoid any program crashes.

RELATED TAGS

python
azure
communitycreator
RELATED COURSES

View all Courses

Keep Exploring