python
azure
5 years, 4 months ago
from contextlib import contextmanager
import datetime
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
@contextmanager
def session_scope():
session = Session(engine)
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
def to_dict(row):
d = {}
for column in row.__table__.columns:
d[column.name] = getattr(row, column.name)
return d
cs = "mssql+pyodbc://<username>:<pwd>@<dbname>.database.windows.net/?driver=ODBC+Driver+17+for+SQL+Server"
engine = create_engine(cs)
metadata = MetaData()
metadata.reflect(engine)
Base = automap_base(metadata=metadata)
Base.prepare(engine, reflect=True)
my_table = Base.classes.TableName
with session_scope() as session:
records = session.query(my_table).all()
for row in records:
# print(row.column_name1, row.column_name2)
print(to_dict(row))
0 Comments
Please Login to Comment Here