Created
April 25, 2019 09:49
-
-
Save eshirazi/e381fec4e9563d9088c4e642037bb4a5 to your computer and use it in GitHub Desktop.
SQLAlchemy connect to Azure SQL, using PyODBC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Thanks! There are a lot of examples online that are not quite right. This one is great!
How can i use ORM for Azure sql?
Can you please suggest..
pip install pyodbc sqlalchemy
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)
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
Great!