CData Python Connector for DB2

Build 20.0.7745

Querying Data

After connecting with the steps in Connecting, you can query data using a session object.

Model Data Using a Mapping Class

Declare a mapping class for the table you wish to model in the ORM. This is done using "sqlalchemy.ext.declarative.declarative_base". A known table in the data model is modeled either partially or completely as in the below example:
import sqlalchemy.ext.declarative.declarative_base
Base = declarative_base()
class Books(Base):
	__tablename__ = "Books"
	Id = Column(String, primary_key=True)
	Id = Column(String)
	Author = Column(String)

Querying Data Using the Query Method

If the mapping class has been prepared, it is used alongside a session object to query the data source. After binding the engine to the session, simply provide the mapping class to the session's query method, as below:

engine = create_engine("cdata_DB2:///?Server=;Port=50000;User=admin;Password=admin;Database=test")
factory = sessionmaker(bind=engine)
session = factory()
for instance in session.query(Books).filter_by(Category="US"):
	print("Id: ", instance.Id)
	print("Id: ", instance.Id)
	print("Author: ", instance.Author)

Querying Data Using the Execute Method

As an alternative, the session object can also run the query with the execute() method alongside the appropriate Table object. Assuming you have an active session, the below should be just as viable:

Books_table = Books.metadata.tables["Books"]
for instance in session.execute( == "US")):
	print("Id: ", instance.Id)
	print("FullName: ", instance.Name)
	print("City: ", instance.BillingCity)

Copyright (c) 2021 CData Software, Inc. - All rights reserved.
Build 20.0.7745