1

I would like to transfer most of my code written on T-SQL to Python, and came across basic data problems that could not be solved by searching in the SQLAlchemy documentation and in other forums.

Question:

How can I implement the following query options with SQLAlchemy (example for the test - below)?

  1. select a.field1, a.field2, b.field2 from server1.database1.schema1.table_a as a inner server2.database1.schema1.table_b as b on a.fileld1 = b.fileld1

  2. select a.field1, a.field2, b.field2 from server1.database1.schema1.table_a as a inner dataset_variable (**) as b on a.fileld1 = b.fileld1

  3. The result of the query - print (select) (see below in the test case) returns an error: sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42S02', "[42S02] [M icrosoft] [ODBC SQL Server Driver] [SQL Server] Invalid object name 'server2.database1schema1.table_b'.

** Data received from another SQLAlchemy session (server2.database1.schema1.table_b) and stored in the variable dataset_variable

Test connection example: Two linked sql servers are used.

engine = create_engine("mssql+pyodbc://@{server1}/{}?driver=SQL+Server?trusted_connection=yes", echo=True)

metadata = MetaData(engine)
Base = declarative_base(metadata=metadata)

class table_a(Base):
    __tablename__ = 'table_a '
    __table_args__ = {
    'schema': 'database1.schema1'
    }
    id = Column(Integer, primary_key=True)
    f1 = Column(String(100))
    f2 = Column(String(100))

class table_b(Base):
    __tablename__ = 'table_b '
    __table_args__ = {
    'schema': 'server2.database1.schema1'
    }
    id = Column(Integer, primary_key=True)
    f1 = Column(String(100))
    f2 = Column(String(100))

Session = sessionmaker(bind=engine)
session = Session()

select = session.query(table_b.id).first() 
print(select)
Kian
  • 1,319
  • 1
  • 13
  • 23
zs_vasily
  • 103
  • 1
  • 8
  • Regarding the schema naming issue (your 3. item in the list, and from your previous question about the same subject): what version of SQLAlchemy are you using? – Ilja Everilä Dec 18 '17 at 13:11
  • Ilja Everilä, thank you for helping! Using version sqlalchemy: 1.2.0b3. I found answer for my question in this topic, maybe you're also be interesting to see it: https://stackoverflow.com/questions/1857465/with-sqlalchemy-how-to-dynamically-bind-to-database-engine-on-a-per-request-basi/1858010#18580 – zs_vasily Dec 18 '17 at 14:48

0 Answers0