Python使用ibm_dbi遍历游标实现DB2游标循环逻辑问题
Hey there! Let's figure out how to translate that DB2 cursor loop logic into Python using ibm_db_dbi. I'll walk you through each part step by step, matching what your original DB2 code does.
First: Traverse the Query Results to Get Table Names
After executing your initial SQL query, you can loop through the cursor directly to fetch each row. Each row will contain the NAME value from your SELECT statement—here's how to grab it:
# Make your connection (I'll assume this part is working for you!) conn = ibm_db_dbi.connect("DATABASE=%s;HOSTNAME=%s,..." % (your_db, your_host)) cur = conn.cursor() # Your original SQL query (fixed a small syntax typo in the JOIN clause, by the way!) sql = """ SELECT S.NAME FROM SYSIBM.SYSTABLES AS S JOIN (SELECT DISTINCT TBNAME FROM SYSIBM.SYSCOLUMNS WHERE CREATOR = 'SOME_SCHEMA_DB') AS C ON C.TBNAME = S.NAME WHERE S.CREATOR = 'SOME_SCHEMA' AND S.TYPE = 'T' """ # Execute the query and loop through results cur.execute(sql) for row in cur: table_name = row[0] # Since we selected S.NAME, it's the first (and only) column # We'll add the rest of the logic here next!
Next: Replicate the DB2 Loop Logic
Your original DB2 code does two key things per table:
- Creates a qualified table name like
SCHEMA1.table_name - Checks if that table exists in
SCHEMA1, then selects 1 into a temp table (I'll assume this means inserting a record intoTEMP_TABLEif the table exists)
Here's how to do that in Python:
# Define your SCHEMA1 value (replace with your actual schema name) schema1 = "SCHEMA1" cur.execute(sql) for row in cur: table_name = row[0] # Step 1: Build the qualified table name (equivalent to SCHEMA1 ||'.'||v.Name) qualified_table = f"{schema1}.{table_name}" # Step 2: Check if the table exists in SCHEMA1 (matches your SELECT 1 ... logic) # Use parameterized queries to avoid SQL injection and handle variables safely check_table_sql = """ SELECT 1 FROM SYSIBM.SYSTABLES WHERE TYPE='T' AND CREATOR = ? AND NAME = ? """ # Use a new cursor for this check (keeps things clean) check_cur = conn.cursor() check_cur.execute(check_table_sql, (schema1, table_name)) table_exists = check_cur.fetchone() if table_exists: # If the table exists, insert 1 into TEMP_TABLE (like your SELECT INTO logic) insert_sql = "INSERT INTO TEMP_TABLE VALUES (?)" insert_cur = conn.cursor() insert_cur.execute(insert_sql, (1,)) conn.commit() # Commit the change if your connection isn't set to auto-commit print(f"Added entry for existing table: {qualified_table}") else: print(f"Table {qualified_table} does not exist in {schema1}") # Clean up cursors after use to free resources check_cur.close() insert_cur.close() # Don't forget to close your main cursor and connection when done cur.close() conn.close()
Quick Notes to Keep in Mind:
- Parameterized Queries: I used
?as placeholders instead of string concatenation for the schema and table names—this is critical to avoid SQL injection and handle any special characters in names. - Transaction Control: If you're modifying data (like inserting into
TEMP_TABLE), you'll need to callconn.commit()unless your connection is configured for auto-commit. - Resource Cleanup: Always close cursors and connections when you're done to avoid leaving unused database connections open.
- Syntax Fix: I fixed a small typo in your original SQL (changed
AS C.TBNAMEtoAS C ON C.TBNAME—that was a missing JOIN clause keyword!).
内容的提问来源于stack exchange,提问作者Anthony Potter
相关产品推荐
相关产品推荐

