I am trying to use pandas.read_sql_table to get data from MS SQL Server (the server is on a network). I use Windows authentication to access the server. Pandas read_sql_table takes a SQL Alchemy connection as an argument for “connection.” I am having a difficult time finding an example that combines:
- SQL Alchemy
- MS SQL Server
- DSN (the “preferred” specification according to SQL Alchemy)
- Windows authentication
I’ve consulted SQL Alchemy, which shows an example using SQL authentication, but not Windows authentication. http://docs.sqlalchemy.org/en/latest/dialects/mssql.html#connecting-to-pyodbc Here are various options I have tried. All return an error.
import pandas as pd
from sqlalchemy import create_engine
import pyodbc
# set some variables
dbname = 'mydbname'
schemaname = 'myschemaname'
servername = 'myservername'
tablename = ‘mytablename’
sqlcon = create_engine('mssql+pyodbc://@' + servername)
#sqlcon = create_engine('mssql+pyodbc://' + servername + '/' + dbname)
#sqlcon = create_engine('mssql+pyodbc://' + servername)
#sqlcon = create_engine('mssql://' + servername + '/' + dbname + '?trusted_connection=yes')
#sqlcon = create_engine('mssql+pyodbc://' + servername + '/' + dbname + '?trusted_connection=yes')
mydataframe = pd.read_sql_table(tablename,con=sqlcon,schema=schemaname)
The error I get is this:
(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)
What is especially perplexing is the comment about no default driver being specified. None of the examples refer to specifying a default driver when I use this DSN format.
I have consulted this example, which also fails for me: How do I connect to SQL Server via sqlalchemy using Windows Authentication?
I can connect fine with SSMS. I'm using python 3.6.
engine = create_engine("mssql+pyodbc://user:pwd@my_dsn")