Skip to content

Instantly share code, notes, and snippets.

@eshirazi
Created April 25, 2019 09:49
Show Gist options
  • Save eshirazi/e381fec4e9563d9088c4e642037bb4a5 to your computer and use it in GitHub Desktop.
Save eshirazi/e381fec4e9563d9088c4e642037bb4a5 to your computer and use it in GitHub Desktop.
SQLAlchemy connect to Azure SQL, using PyODBC
# On mac, run these first:
# - brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
# - brew update
# - brew install msodbcsql17 mssql-tools
#
# Install requirements:
# - pip install pyodbc sqlalchemny
import urllib
from sqlalchemy import create_engine
server = "<YOUR_AZURE_DB_NAME>.database.windows.net"
database = "<DB NAME>"
username = "<USER NAME>"
password = "<PASSWORD>"
driver = '{ODBC Driver 17 for SQL Server}'
odbc_str = 'DRIVER='+driver+';SERVER='+server+';PORT=1433;UID='+username+';DATABASE='+ database + ';PWD='+ password
connect_str = 'mssql+pyodbc:///?odbc_connect=' + urllib.quote_plus(odbc_str)
print connect_str
engine = create_engine(connect_str)
print engine.execute("SELECT 1").fetchall()
@vinicius-solon-silva
Copy link

Great!

@dr-snglr
Copy link

Thanks! There are a lot of examples online that are not quite right. This one is great!

@anandadake
Copy link

How can i use ORM for Azure sql?
Can you please suggest..

@Shiva0809
Copy link

pip install pyodbc sqlalchemy

@Kahuna-Honu
Copy link

Thank you.

Also, to anyone using a current version of urllib please, change this:
urllib.quote_plus(odbc_str)

to this:
urllib.parse.quote_plus(odbc_str)

@rasmusJul
Copy link

I need to use authorization level : Azure Active Directory interactive. Anyone how knows how to use this level?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment