pyodbc to sqlalchemy connection

心已入冬 提交于 2021-02-19 07:16:26

问题


I am trying to switch a pyodbc connection to sqlalchemy. The working pyodbc connection is:

import pyodbc
con = 'DRIVER={ODBC Driver 11 for SQL Server};SERVER=server.com\pro;DATABASE=DBase;Trusted_Connection=yes'
cnxn = pyodbc.connect(con)
cursor = cnxn.cursor()
query = "Select * from table"
cursor.execute(query)

I tried:

from sqlalchemy import create_engine
dns = 'mssql+pyodbc://server.com\pro/DBase?driver=SQL+Server'
engine = create_engine(dns)
engine.execute('Select * from table').fetchall()

Based on: http://docs.sqlalchemy.org/en/latest/core/engines.html

and: pandas.read_sql() is MUCH slower when using SQLAlchemy than pyodbc

(trying to setup a connection with Trusted_Connection = Yes)

But I receive the message:

OperationalError: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]No existe el servidor SQL Server o se ha denegado el acceso al mismo. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)') (Background on this error at: http://sqlalche.me/e/e3q8) (Sorry for the spanish but it says that the SQL Server doesn't exist)

I am almost sure that it has to do with me not understanding the sintax for the engine connection. Could someone please explain me in detail how to convert the conection from pyodbc to sqlalchemy?

Thanks in advance!

PD: I am trying to implement sqlalchemy to use later in my code pandas.DataFrame.to_sql(engine)


回答1:


I remember having similar issues getting sqlalchemy setup. I've attached my engine statement syntax. I don't remember the details, but I do remember the driver selection being a real pain point. I believe I had to download the ODBC 13 driver separately, but can confirm pd.read_sql() and df.to_sql are working like a charm now.

driver = 'ODBC+DRIVER+13+for+SQL+Server'
engine_stmt = ("mssql+pyodbc://%s:%s@%s/%s?driver=%s" % (username, password, server, database, driver )
engine = sqlalchemy.create_engine(engine_stmt)


来源:https://stackoverflow.com/questions/52450659/pyodbc-to-sqlalchemy-connection

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