I have installed:
- Ubuntu (18.04)
- Python (3.6.8)
- msodbcsql17 (Microsoft ODBC Driver 17 for SQL Server)
- SQLAlchemy (1.3.5)
- Pandas (0.24.2)
and I want to create just a proof of concept using SQLAlchemy with an Azure SQL Data Warehouse. However, when I try to run a query on Customer model which is mapped to the customers view table using the code:
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()
the following exception is thrown:
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)
Please, keep in mind that I can use the SQLAlchemy's engine with pandas and run native SQL queries such:
data_frame = pandas.read_sql("SELECT COUNT(*) FROM customers", engine)
However, my need is to use the high-level query API of SQLAlchemy:
customers_count = session.query(Customer).count()
Any help would be really appreciated.
Session = sessionmaker(bind=engine, autocommit=True)
– Balkanizeautocommit=False
) causes SQLAlchemy to sendBEGIN (implicit)
immediately before running theSELECT count(*) ...
statement to count the number of rows in the table. Specifyingautocommit=True
suppresses theBEGIN (implicit)
statement, which Azure SQL DW apparently ignores. – Balkanizeautocommit=True
the linesession.query(Customer).count()
will not send theBEGIN (implicit)
statement. I would like to ask something more: It is possible to useengine.execute(query).execution_options(autocommit=True)
and alsocreate_engine(connectionString, connect_args={'autocommit': True))
. What are these for? Should I useautocommit=True
only in sessionmaker? – Yorgos