CData Python Connector for DB2

Build 20.0.7745

Querying Data

After connecting with the steps in Connecting, you can execute a SQL statements using the connection's cursor object.

Executing Queries

To execute SQL statements that return data, use the cursor object's execute method. Once a query is executed, the result set is fetched from the cursor. This result set can then be iterated over to process the records individually:

import cdata.DB2 as mod
conn = mod.connect("Server=10.0.1.2;Port=50000;User=admin;Password=admin;Database=test")
cur = conn.cursor()
cur.execute("SELECT Id, Author FROM Books")
rs = cur.fetchall()
for row in rs:
	print(row)

Parameterized Queries

Various python collections, such as arrays and tuples are provided as additional arguments for the execute method. This allows you to parameterize the queries executed and help to prevent SQL Injection:

import cdata.DB2 as mod
conn = mod.connect("Server=10.0.1.2;Port=50000;User=admin;Password=admin;Database=test")
cur = conn.cursor()
cmd = "SELECT Id, Author FROM Books WHERE Category = ?"
params = ["US"]
cur.execute(cmd, params)
rs = cur.fetchall()
for row in rs:
	print(row)

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