Connect to MS SQL on a network with SQL Alchemy in Python using Windows Authentication

*爱你&永不变心* 提交于 2019-12-11 18:09:43

问题


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:

  1. SQL Alchemy
  2. MS SQL Server
  3. DSN (the “preferred” specification according to SQL Alchemy)
  4. 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.


回答1:


I found a solution to my question. Posting here for others' reference.

This code worked. I wasn't able to avoid specifying a driver explicitly, though.

sqlcon = create_engine('mssql+pyodbc://@' + servername + '/' + dbname + '?driver=ODBC+Driver+13+for+SQL+Server')


来源:https://stackoverflow.com/questions/49947098/connect-to-ms-sql-on-a-network-with-sql-alchemy-in-python-using-windows-authenti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!