SQLAlchemy错误:尝试完成事务失败。找不到对应的交易

时间:2019-07-20 10:05:11

标签: python sqlalchemy pyodbc azure-sql-data-warehouse msodbcsql17

我已经安装:

  • Ubuntu(18.04)
  • Python(3.6.8)
  • msodbcsql17(用于SQL Server的Microsoft ODBC驱动程序17)
  • SQLAlchemy(1.3.5)
  • 熊猫(0.24.2)

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

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的引擎与熊猫一起使用,并运行本机SQL查询,例如:

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

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

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

任何帮助将不胜感激。

0 个答案:

没有答案