Python 连接 DB2 库有几种方式,本次以 IBM 出的 ibm_db 方式为例,网上东拼西凑加自己改,封装了一个调用的方法,废话不多说,直接上介绍
Python 连接 DB2 库方式:https://wiki.python.org/moin/DB2
环境准备
pip install setuptools(依赖工具包)
easy_install ibm_db(IBM 的工具包)
代码实例
IbmDBOperate.py(连库、查询方法)
注:SELECT 语句中的表名等需要换成实际存在的表名
conn 为获取数据库链接时需要用到的参数,我把参数抽到了一个 config.py 里,如果不想抽出来,去掉 config 的 import,和 key=一行,直接用注掉的 # conn 方法即可
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#########################
# excute python2.7.13
# sudo pip install ibm_db
#########################
import ibm_db
from fastAutoTest.config import config
def connectDataBase():
pass
try:
key = "DATABASE=" + config.database + ";HOSTNAME=" + config.hostname + ";PORT=" + config.port + ";PROTOCOL=TCPIP; UID=" + config.user + ";PWD=" + config.password
# conn = ibm_db.connect("DATABASE=upontest;HOSTNAME=10.10.73.95;PORT=60000;PROTOCOL=TCPIP; UID=usaasfta;PWD=usaasfta", "", "")
conn = ibm_db.connect(key,"","")
except:
print("connect failed,%s" % ibm_db.conn_errormsg())
return conn
def findStoreINFByStoreShortName(storeShortName):
connect = connectDataBase()
sql = "SELECT * FROM UMPAY.T_STORE_INF WHERE STORE_SHORT_NAME ='" + storeShortName +"' "
sql_u = sql.decode('utf-8')
print "执行SQL语句:" + sql
try:
stmt = ibm_db.exec_immediate(connect, sql_u)
dictionary = ibm_db.fetch_both(stmt)
except:
print("stmt failed,%s" % ibm_db.stmt_errormsg())
finally:
if ibm_db.active(connect):
ibm_db.close(connect)
print("database close success!")
return dictionary
test.py(调用封装好的 findStoreINFByStoreShortName)
# coding=utf-8
import config
from fastAutoTest.utils import IbmDbOperate
if __name__ == '__main__':
result = IbmDbOperate.findStoreINFByStoreShortName("测试192223")
print result["REGISTER_PROCS_STATE"]
self.assertEqual(result["REGISTER_PROCS_STATE"], '03')
执行结果
参考文档:
https://www.cnblogs.com/fushou/p/7388089.html
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.5.0/com.ibm.db2.luw.apdv.python.doc/doc/t0054368.html