Python测试DB2连通性

本文介绍了一个使用Python脚本测试IBM DB2数据库连接的方法。该脚本从配置文件中读取数据库连接参数,并尝试建立连接。如果连接成功,则返回1;若失败则返回0。文中提供了一个具体的Python脚本示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python测试数据库连通性:

#!/usr/bin/python27
#encoding: utf-8
import ibm_db
import os
import sys
def find_db(filename,db_name):
    f = open(filename)
    for line in f:
        file_db = line.strip().split(',')[0]
        if file_db == db_name:
            db_list = line.strip().split(',')
            break
    f.close()
    return db_list

def test_conn(db_name,db_host,db_port,db_user,db_pwd):
    db2 = "DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s;" %(db_name,db_host,db_port,db_user,db_pwd)
    try:
        conn = ibm_db.connect(db2, "", "")
    except:
        print "0"
    else:
        print "1"
        ibm_db.close(conn)

if __name__ == "__main__":
    file_path = os.path.join(os.path.split(os.path.realpath(__file__))[0],'db1.cfg')
    conn_db = find_db(file_path,sys.argv[1])
    db_name,db_host,db_port,db_user,db_pwd = tuple(conn_db)
    test_conn(db_name,db_host,db_port,db_user,db_pwd)

 

 db.cfg

PTEST1,192.168.2.180,50000,db2inst1,db2inst1
PTEST,192.168.2.180,50001,db2inst1,db2inst1

PTEST2,192.168.2.180,50000,db2inst1,db2inst1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值