我已经安装了:
- Ubuntu (18.04)
- 蟒蛇(3.6.8)
- msodbcsql17(用于 SQL Server 的 Microsoft ODBC 驱动程序 17)
- SQLAlchemy (1.3.5)
- 熊猫 (0.24.2)
我只想使用带有 Azure SQL 数据仓库的 SQLAlchemy 创建概念证明。但是,当我尝试在使用代码映射到客户视图表的客户模型上运行查询时:
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()
任何帮助将非常感激。