Trend
Trend

Reputation: 11

How to connect to Azure sql database through python anaconda jupyter

I am trying to connect to azure sql database through Jupyter notebook and later to load the data into excel/csv .I have the details of server and database only .Username & password i think by default its taking my desktop credentials(unsure).

Here is tried code

import pyodbc 
cnxn = pyodbc.connect(Server=myserver;Database=mydatabase)

Upvotes: 0

Views: 1601

Answers (2)

Lidor Eliyahu Shelef
Lidor Eliyahu Shelef

Reputation: 1332

In order to connect to your Azure SQL database with your jupyter notebook use the following:

import pyodbc

server = 'tcp:SQLSERVER.database.windows.net' # Server example
database = '<INSERT DATABASE NAME>' 
username = '<INSERT USERNAME>' 
password = '<INSER PASSWORD>' 
driver= '{ODBC Driver 17 for SQL Server}' # Driver example
connection= pyodbc.connect('DRIVER=' + driver + ';SERVER=' +server + ';PORT=1433;DATABASE=' + database +';UID=' + username + ';PWD=' + password)

cursor = connection.cursor() # Just something you can do
print(connection)
connection.close()

For more details you can refer to the following links:

  1. Connect to Azure SQL Database using Python and Jupyter Notebook
  2. Connect to Azure SQL Database in a Jupyter Notebook using Python
  3. Quickstart: Use Python to query a database

Upvotes: 2

Aswin
Aswin

Reputation: 7156

You need to give username, password of the Azure SQL database in connextion. Below is the code to establish connection of Azure SQl database using python in Jupyter Notebook.

import pyodbc
# Establish the connection
server =  'xxxxx.database.windows.net'
database =  'xxx'
username =  'xxxx'
password =  'xxxx'
driver=  '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect('DRIVER='  + driver +  ';SERVER='  +
server +  ';PORT=1433;DATABASE='  + database +
';UID='  + username +  ';PWD='  + password)
print(conn)
conn.close()

enter image description here

Reference: Use Python to query a database - Azure SQL Database & SQL Managed Instance | Microsoft Learn

Upvotes: 0

Related Questions