Connecting to the SQL database

Communication between Python and Azure SQL Database requires using the pyodbc ODBC database driver:

MA-Creating-SQL-database-14

Let’s use the pip command (a package-management system to install packages from the Python library) to install the ODBC driver:

pip install pyodbc

After pyodbc installation we are ready to write the Python code to connect to the database:



import pyodbc

server = 'ccsqlserver0546.database.windows.net'
database = 'ccDatabase'
username = 'ccazureuser'
password = 'YOUR_PASSWORD'
driver= '{ODBC Driver 13 for SQL Server}'

cnxn = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()