AsitK
AsitK

Reputation: 673

Getting ODBC Driver 17 error while connecting to azure SQL

I'm getting the following error while connection my code to azure SQL from local machine (windows) and also when deployed to azure function (python/linux)

sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: A non-recoverable error occurred during a database lookup.\r\n (11003) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (11003)')

I'm able to connect to the SQL server using SQL Server management studio

my sample code for connecting to SQL server

from sqlalchemy import create_engine
connection_string = "mssql+pyodbc://user:[email protected]/mydatabase?driver=ODBC+Driver+17+for+SQL+Server" 
self.engine = create_engine(connection_string, pool_size=100, max_overflow=20)
self.engine.connect()

Upvotes: 1

Views: 1457

Answers (1)

Alberto Morillo
Alberto Morillo

Reputation: 15648

Please add the following items on the connection string:

;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"

Below a full example on how to connect from SqlAlchemy that I extracted from this other question.

import urllib
from sqlalchemy import create_engine,text
import pandas as pd

server   = 'servername.database.windows.net'
database = 'databasename'
username = 'username'
password = 'password!'   
driver   = '{ODBC Driver 17 for SQL Server}'

conn = f"""Driver={driver};Server=tcp:{server},1433;Database={database};
Uid={username};Pwd={password};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"""

params = urllib.parse.quote_plus(conn)
conn_str = 'mssql+pyodbc:///?autocommit=true&odbc_connect={}'.format(params)
engine = create_engine(conn_str, echo=True)

query = 'SELECT @@version'

with engine.connect() as connection:
    df = pd.read_sql_query(sql=text(query), con=connection)
print(df.to_markdown())

Upvotes: 2

Related Questions