SQL Server Python SQLAlchemy: Data source name not found and no default driver specified

daupos2t  于 2023-02-28  发布在  Python
关注(0)|答案(4)|浏览(244)

Using Python: when connecting to SQL Server using pyodbc, everything works fine, but when I switch to sqlalchemy, the connection fails, giving me the error message:

('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

My code:

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=dbname;UID=username;PWD=password')
engine = sqlalchemy.create_engine("mssql+pyodbc://username:password@servername/dbname")

I can't find the error in my code, and don't understand why the first options works, but the second doesn't.

Help is highly appreciated!

hgc7kmma

hgc7kmma1#

Ran into this problem as well, appending a driver query string to the end of my connection path worked:

"mssql+pyodbc://" + uname + ":" + pword + "@" + server + "/" + dbname + "?driver=SQL+Server"

Update (July 2021) – As above, just modernized (Python 3.6+):

f"mssql+pyodbc://{uname}:{pword}@{server}:{port}/{dbname}?driver=ODBC+Driver+17+for+SQL+Server"

Note that driver= must be all lowercase.

wxclj1h5

wxclj1h52#

It works using pymssql, instead of pyodbc.

Install pymssql using pip, then change your code to:

engine = sqlalchemy.create_engine("mssql+pymssql://username:password@servername/dbname")
0tdrvxhp

0tdrvxhp3#

Very late, but experienced the same such problem myself recently. Turned out it was a problem with the latest SQLAlchemy version. Had to rollback my version from 1.4.17 to 1.4.12 (unsure of in-between versions, just went with a version I knew worked).

pip install sqlalchemy==1.4.12
nszi6y05

nszi6y054#

I had original poster's problem with a trusted connection to the Microsoft SQL Server database (pandas 1.5.3, SQLAlchemy 2.0.4). Using answers from this question, this did the trick for me:

import sqlalchemy
import pandas as pd

server = "servername"
database = "dbname"
driver = "ODBC+Driver+17+for+SQL+Server"
url = f"mssql+pyodbc://{server}/{database}?trusted_connection=yes&driver={driver}"
engine = sqlalchemy.create_engine(url)
    
query = """
    SELECT [column1]
    ,[column2] as some_other_name
    FROM [server].[dbo].[table]"""

with engine.begin() as conn:
    sqla_query = sqlalchemy.text(query)
    df = pd.read_sql(sqla_query, conn)

It should be noted that pandas is not yet fully compatible with SQLAlchemy 2.0: https://pandas.pydata.org/docs/whatsnew/v1.5.3.html

相关问题