3
votes

I am trying to connect to the SQL server database on python platform using SqlAlchemy. I am using windows authentication to connect to my the SQL server. On connecting the server the SqlAlchemy engine is throwing an error:

Below is the code I have implemented:

import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import pyodbc


              Driver         Server Name    Instance        Database
DATABASE_URL='mssql+pyodbc://DESKTOP-N32LSOV\PRANAV/AdventureworksDW2016CTP3?trusted_connection=yes'
Engine = create_engine(DATABASE_URL)

cn = Engine.connect()

When the above code is run, this error is produced:

Error:sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') (Background on this error at: http://sqlalche.me/e/rvf5)

I tried using pymssql driver inplace of pyodbc driver but still the error persists. On contrary when i try to connect to the using the below syntax it connects. I guess i am missing some attribute in the mssql url.

pyodbc.connect(r'Driver={SQL Server};Server=DESKTOP-N32LSOV\PRANAV;Database=master;Trusted_Connection=yes;')

Any help will be appreciated.

2
The problem is that you have not escaped the backslash in DATABASE_URL. So either use a r""-string or escape the backslash (\\). In your pyodbc.connect()-call, you use r""-syntax.codeape
@codeape Hi man i tried "mssql+pyodbc://DESKTOP-N32LSOV\PRANAV:1433//AdventureworksDW2016CTP3?driver=SQL+Server+Native+Client+10.0". Also tried "mssql+pyodbc://DESKTOP-N32LSOV\\PRANAV:1433/AdventureworksDW2016CTP3?driver=SQL+Server+Native+Client+10.0". didn't helpuser10532073

2 Answers

0
votes

You need to specify both that you want to use ODBC and what ODBC driver to use.

engine = sqlalchemy.create_engine('mssql+pyodbc://localhost/Sandbox?driver=SQL+Server+Native+Client+11.0')

If you add the driver= part to your database url, it should work.

0
votes

If all else fails, I would try using the creator argument to create_engine (documentation):

def creator():
    return pyodbc.connect(r'Driver={SQL Server};Server=DESKTOP-N32LSOV\PRANAV;Database=master;Trusted_Connection=yes;')

Engine = create_engine('mssql://', creator=creator)

Using creator= bypasses all connection parameters specified in the URL, so you should only pass information to specify the DB dialect in the URL.

Looking at the mssql+pyodbc dialect/driver documentation, there is also the ?odbc_connect option:

import urllib.parse
CONNECTION_STRING = r'Driver={SQL Server};Server=DESKTOP-N32LSOV\PRANAV;Database=master;Trusted_Connection=yes;'
Engine = create_engine('mssql+pyodbc:///?odbc_connect=' + urllib.parse.quote_plus(CONNECTION_STRING))