本文中的示例代码功能点
DB2提取查询结果有四种方式
1 2 3 4 5 6 7 8 9 10 11
| 1.先调用fetch_row(stmt),有结果返回true否则返回false,再调用ibm_db.result(stmt, col_idx)提取结果 ibm_db.fetch_row(stmt) result = ibm_db.result(stmt, 0) 2.调用fetch_both(stmt)提取一行,返回的结果是一个字典,取值可以用列名或索引 result["MOBILE"]或 result[0] result = ibm_db.fetch_both(stmt) 3.调用fetch_assoc(stmt)提取一行,返回的是一个字典,取值只能用列明 result["MOBILE"] result = ibm_db.fetch_assoc(stmt) 4.调用fetch_tuple(stmt)提取一行,返回的是一个元组,取值只能用索引 result[0] result = ibm_db.fetch_tuple(stmt)
注: ibm_db没办法一次提取多行,提取多行数据,需要循环提取
|
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import os import ibm_db
db_url = "DATABASE=moiac;SCHEMA=moiase;HOSTNAME=199.188.166.110;PORT=60000;PROTOCOL=TCPIP;UID=moiase;PWD=moiase;"
tab_name = "t04_job_param"
file_name = "%s.sql" % (tab_name)
if os.path.exists(file_name): os.remove(file_name)
select_sql = """select * from %s""" % (tab_name)
try: conn = ibm_db.connect(db_url, "", "") ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) stmt = ibm_db.exec_immediate(conn, select_sql) res = ibm_db.fetch_assoc(stmt) num = 0 while (res): num += 1 print("第" + str(num) + "行") key = ','.join(str(k) for k in res.keys()) val = ','.join( '\'' + str(v) + '\'' if isinstance(v, str) else str(v) for v in res.values()) ins_str = "insert into %s (%s) values (%s);" % (tab_name, key, val) with open(file_name, 'a') as file: file.write(ins_str + "\n") file.close() res = ibm_db.fetch_assoc(stmt) print(("%s生成完成, 共%s条数据") % (tab_name, num)) ibm_db.commit(conn) except Exception as e: print(e) ibm_db.rollback(conn) finally: ibm_db.close(conn)
|
蚂蚁🐜再小也是肉🥩!