'Python MicrosoftSQL connection error using pandas and SQLAlchemy
I have a script that uses pandas to query a microsoft sql database and enter the results in an excel workbook.
import pyodbc
import pandas as pd
from sqlalchemy import create_engine
cnxn = create_engine('mssql+pyodbc://connection.info.here')
sql_query = """
QUERY
"""
df = pd.read_sql_query(sql_query, cnxn)
writer = pd.ExcelWriter('foo.xlsx')
df.to_excel(writer, sheet_name='bar')
writer.save()
When I run the script it looks like it's working - it takes a little bit, but then it returns this error in the stacktrace.
sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
I know the query works because I get the expected results in Microsoft SQL Management Studio in about 10 seconds.
Solution 1:[1]
So it turns out that since I'm using a hostname and not an IP address for the database in my connection string i have to specify the driver.
It would look like this.
cnxn = create_engine("mssql+pyodbc://user:password@hostname:port/databasename?driver=SQL+Server")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | iNeedScissors61 |
