How do I set the schema in SQLAlchemy for MSSQL?
If you load metadata from the database and load table from the metadata, you can set the schema during table load.
Then create a session and query the table
from sqlalchemy import MetaData, Table
from sqlalchemy.orm import sessionmaker
table = Table({Table Name}, {metadata}, autoload=True, autoload_with={engine}, schema={Schema name})
Session = sessionmaker()
Session.configure(bind={engine})
session = Session()
query = session.query(table)
Reading this SO Question Possible to set default schema from connection string? it seems not possible to select schema using connection string.
try a full qualified name :
sql = ('SELECT foo FROM exampleschema.bar;')
You can also specify the schema name in the class definition (is not your specific case but I think it's a common situation).
For example, if you have a table "dog" into the "animal" schema:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Notification(Base):
__tablename__ = "dog"
__table_args__ = {"schema": "animal"}
id = Column(Integer, primary_key=True)
name = Column(String)