SQLAlchemy error: An attempt to complete a transaction has failed. No corresponding transaction found

SQLAlchemy error: An attempt to complete a transaction has failed. No corresponding transaction found

我已经安装:

我只想使用 SQLAlchemy 和 Azure SQL 数据仓库创建一个概念证明。但是,当我尝试 运行 查询映射到客户视图 table 的客户模型时,使用代码:

import urllib

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

db_username = 'username'
db_password = 'password'
db_database = 'dbname'
db_hostname = 'dbhost'
db_driver = 'ODBC Driver 17 for SQL Server'
db_port = '1433'

db_connectionString = f"DRIVER={{{db_driver}}}; SERVER={{{db_hostname}}}; DATABASE={{{db_database}}}; UID={{{db_username}}}; PWD={{{db_password}}}; PORT={{{db_port}}};"

engine_params = urllib.parse.quote_plus(db_connectionString)

engine = create_engine(f"mssql+pyodbc:///?odbc_connect={engine_params}", echo=True)

Base = declarative_base()

class Customer(Base):
    __tablename__ = 'customers'

    id = Column('Customer_ID', Integer, primary_key=True)

Session = sessionmaker(bind=engine)
session = Session()

customers_count = session.query(Customer).count()

session.close()

抛出以下异常:

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)

请记住,我可以将 SQLAlchemy 的引擎与 pandas 和 运行 本机 SQL 查询一起使用,例如:

data_frame = pandas.read_sql("SELECT COUNT(*) FROM customers", engine)

但是,我的需要是使用 SQLAlchemy 的高级查询 API:

customers_count = session.query(Customer).count()

任何帮助将不胜感激。

mssql+pyodbc://… 的 SQLAlchemy 文档刚刚更新为包括以下内容(对于 SQLA 1.4/2.0):

Azure SQL Data Warehouse does not support transactions, and that can cause problems with SQLAlchemy's "autobegin" (and implicit commit/rollback) behavior. We can avoid these problems by enabling autocommit at both the pyodbc and engine levels:

connection_url = sa.engine.URL.create(
    "mssql+pyodbc",
    username="scott",
    password="tiger",
    host="dw.azure.example.com",
    database="mydb",
    query={
        "driver": "ODBC Driver 17 for SQL Server",
        "autocommit": "True",
    },
)
engine = create_engine(connection_url).execution_options(
    isolation_level="AUTOCOMMIT"
)

添加到@Gord Thompson 的回答(抱歉,我没有足够的声誉来发表评论)。对于 SQLAlchemy 1.4.32;如果您只有模式的管理员权限而不是整个数据库,则设置事务隔离级别将在库检查隔离级别对数据库是否有效时引发错误。为了解决这个问题,我稍微修改了代码。

connection_url = sa.engine.URL.create(
    "mssql+pyodbc",
    username="scott",
    password="tiger",
    host="dw.azure.example.com",
    database="mydb",
    query={
        "driver": "ODBC Driver 17 for SQL Server",
        "autocommit": "True",
    },
)
engine = create_engine(connection_url).execution_options()

这会给你一个警告,但确实有效。