Skip to content

Instantly share code, notes, and snippets.

@Razzo78
Last active January 14, 2023 12:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Razzo78/6b25308cc144b75e42d763690c3224c9 to your computer and use it in GitHub Desktop.
Save Razzo78/6b25308cc144b75e42d763690c3224c9 to your computer and use it in GitHub Desktop.
Python, SQL Server - Connect and get data with SqlAlchemy
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)
@Joragasy
Copy link

Thank's for your post !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment