SQLAlchemy – SQLEndTran – PyODBC vs. Engine

huangapple go评论87阅读模式
英文:

SQLAlchemy - SQLEndTran - PyODBC vs. Engine

问题

这应该是一个简单的问题,但让我感到困扰。

我不能分享所有的细节,但让我们假设我有以下内容:

import pandas as pd
import sqlalchemy
from sqlalchemy.engine import URL

driver='ODBC Driver 17 for SQL Server'
server='MyServer'
database='MyDB'
username = 'MyUser'
password = 'MyPWD'

# pyodbc连接字符串
connection_string = f'DRIVER={driver};SERVER={server};PORT=17001;DATABASE={database};UID={username};PWD={password}'

# 创建SQLAlchemy引擎连接URL
engine = sqlalchemy.create_engine(URL.create("mssql+pyodbc", query={"odbc_connect": connection_string}))

pd.read_sql(sql=Query, con=engine)

ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]111214;An attempt to complete a transaction has failed. No corresponding transaction found. (111214) (SQLEndTran)')
(Background on this error at: https://sqlalche.me/e/14/f405)

链接中提到(我加粗了感兴趣的部分):

ProgrammingError 异常是由编程错误引发的,例如表不存在或已存在,在SQL语句中存在语法错误,指定的参数数量不正确等。

此错误是DBAPI错误,起源于数据库驱动程序(DBAPI),而不是SQLAlchemy本身。

有时,由于数据库连接被断开或无法连接到数据库,驱动程序会引发ProgrammingError。有关如何处理此问题的提示,请参阅“处理断开连接”部分。

我认为问题出在连接上,而不是我的 Query(未显示),因为如果我执行以下操作:

import pyodbc    
cnxn = pyodbc.connect(connection_string)
pd.read_sql(sql=Query, con=cnxn)

查询正常工作,但我会收到Pandas的警告,因为没有使用SQLAlchemy:

C:\Users\AppData\Local\Temp\ipykernel_9716\2299942033.py:1: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy.

您认为我在创建 engine 时做错了什么?

英文:

This should be an easy one but driving me crazy.

I cannot share all the details but lets say I have the following:

import pandas as pd
import sqlalchemy
from sqlalchemy.engine import URL

driver='ODBC Driver 17 for SQL Server'
server='MyServer'
database='MyDB'
username = 'MyUser'
password = 'MyPWD'

# pyodbc connection string
connection_string = f'DRIVER={driver};SERVER={server};PORT=17001;DATABASE={database};UID={username};PWD={password}'

# create sqlalchemy engine connection URL
engine = sqlalchemy.create_engine(URL.create("mssql+pyodbc", query={"odbc_connect": connection_string}))

pd.read_sql(sql=Query, con=engine)

ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]111214;An attempt to complete a transaction has failed. No corresponding transaction found. (111214) (SQLEndTran)')
(Background on this error at: https://sqlalche.me/e/14/f405)

The link reads (I bolded the interesting bit):

> ProgrammingError Exception raised for programming errors, e.g. table
> not found or already exists, syntax error in the SQL statement, wrong
> number of parameters specified, etc.
>
> This error is a DBAPI Error and originates from the database driver
> (DBAPI), not SQLAlchemy itself.
>
> The ProgrammingError is sometimes raised by drivers in the context of
> the database connection being dropped, or not being able to connect to
> the database. For tips on how to deal with this, see the section
> Dealing with Disconnects.

I suppose the connection is to blame and not my Query (not shown) because if I do:

import pyodbc    
cnxn = pyodbc.connect(connection_string)
pd.read_sql(sql=Query, con=cnxn)

The query works fine, but I get the Pandas warning for not using SQLAlchemy:

C:\Users\AppData\Local\Temp\ipykernel_971699942033.py:1: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy.

Any idea what I am doing wrong when creating the engine?

答案1

得分: 1

以下是已翻译的代码部分:

找到了... 以下内容有效

import pandas as pd
import sqlalchemy
from sqlalchemy.engine import URL

driver='ODBC Driver 17 for SQL Server'
server='MyServer'
database='MyDB'
username = 'MyUser'
password = 'MyPWD'

# 创建SQLAlchemy引擎连接URL
connection_url = URL.create("mssql+pyodbc", 
                            username=username, 
                            password=password, 
                            host=server, 
                            database=database, 
                            query={"driver": "ODBC Driver 17 for SQL Server", "autocommit": "True"})

pd.read_sql(sql=Query, con=engine)
英文:

Found it... the following worked:

    import pandas as pd
    import sqlalchemy
    from sqlalchemy.engine import URL
    
    driver='ODBC Driver 17 for SQL Server'
    server='MyServer'
    database='MyDB'
    username = 'MyUser'
    password = 'MyPWD'
    
    # create sqlalchemy engine connection URL
    connection_url = connection_url = URL.create("mssql+pyodbc", 
                                                  username=username, 
                                                  password=password, 
                                                  host=server, 
                                                  database=database, 
                     query={"driver": "ODBC Driver 17 for SQL Server", "autocommit": "True"})
    
    pd.read_sql(sql=Query, con=engine)

答案2

得分: 0

尝试使用SQLAlchemy如下:


with engine.connect() as conn:
    pd.read_sql(sql=Query, con=conn)
英文:

Try using sqlalchemy like this:


with engine.connect() as conn:
    pd.read_sql(sql=Query, con=conn)

huangapple
  • 本文由 发表于 2023年6月22日 00:46:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定