Last active
January 14, 2023 12:06
-
-
Save Razzo78/6b25308cc144b75e42d763690c3224c9 to your computer and use it in GitHub Desktop.
Python, SQL Server - Connect and get data with SqlAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import create_engine, MetaData, Table | |
from sqlalchemy.orm import mapper | |
from sqlalchemy.sql import select | |
class MyTable(object): | |
pass | |
# Trusted Connection | |
engine = create_engine('mssql+pymssql://hostname[\\SQLEXPRESS2008]/dbname') | |
# Password connection | |
# engine = create_engine('mssql+pymssql://username:password@hostname[\\SQLEXPRESS2008]/dbname') | |
metadata = MetaData(engine) | |
my_table_instance = Table('MyTable', metadata, autoload=True) | |
mapper(MyTable, my_table_instance) | |
conn = engine.connect() | |
s = select([MyTable.ColumnName]).where(MyTable.ID == 802) | |
res = conn.execute(s) | |
row = res.fetchone() | |
res = None if row is None else row['ColumnName'] | |
print(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank's for your post !