简体   繁体   中英

SQL Server connection - Works in pyodbc, but not SQLAlchemy

This is a fairly common question but even using the answers on SO like here but I still can't connect.

When I setup my connection to pyodbc I can connect with the following:

cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 11.0};SERVER=ip,port;DATABASE=db;UID=user;PWD=pass')
cursor = cnxn.cursor()

cursor.execute("some select query")
for row in cursor.fetchall():
    print(row)

and it works.

However to do a .read_sql() in pandas I need to connect with sqlalchemy .

I have tried with both hosted connections and pass-through pyodbc connections like the below:

quoted = urllib.parse.quote_plus('DRIVER={SQL Server Native Client 11.0};Server=ip;Database=db;UID=user;PWD=pass;Port=port;')
engine = sqlalchemy.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))
engine.connect()

I have tried with both SERVER=ip,port format and the separate Port=port parameter like above but still no luck.

The error I'm getting is Login failed for user 'user'. (18456) Login failed for user 'user'. (18456)

Any help is much appreciated.

I assume that you want to create a DataFrame so when you have a cnxn you can pass it to Pandas read_sql_query function. Example:

cnxn = pyodbc.connect('your connection string')
query = 'some query'

df = pandas.read_sql_query(query, conn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM