python ibm db_Python Uses ibm_db connect to DB2

本文提供了使用Python连接IBM DB2数据库的三个示例,包括连接本地或目录数据库、未目录数据库及启用SSL的未目录数据库,并展示了如何执行SQL查询。

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

安装好了Python和ibm_db以后,做了几个小例子测试一下

>>> import ibm_db

>>> ibm_db.__version__

'2.0.9'

>>>

=======================================================================

#!/usr/bin/python

#Example 1: Connect to a local or cataloged database

import ibm_db

conn = ibm_db.connect( "dsn=SAMPLE", "db2inst1", "dbpwd" )

sql = "SELECT QUOTEID,GEO FROM DB2INST1.TRN fetch first 10 rows only with ur"

stmt = ibm_db.exec_immediate(conn, sql)

dictionary = ibm_db.fetch_both(stmt)

while dictionary != False:

print(dictionary["QUOTEID"])

print(dictionary["GEO"])

dictionary = ibm_db.fetch_both(stmt)

=======================================================================

#!/usr/bin/python

Example 2: Connect to an uncataloged database

import ibm_db

conn = ibm_db.connect("DATABASE=SAMPLE;HOSTNAME=192.168.101.133;PORT=60006;PROTOCOL=TCPIP;UID=db2inst1;PWD=dbpwd;", "", "")

sql = "SELECT QUOTEID,GEO FROM DB2INST1.TRN fetch first 10 rows only with ur"

stmt = ibm_db.exec_immediate(conn, sql)

dictionary = ibm_db.fetch_both(stmt)

while dictionary != False:

print(dictionary["QUOTEID"])

print(dictionary["GEO"])

dictionary = ibm_db.fetch_both(stmt)

=========================================================================

#!/usr/bin/python

#Example 3: Connect to an uncataloged database with SSL enabled

import ibm_db

conn = ibm_db.connect("DATABASE=SAMPLE;HOSTNAME=192.168.101.133;PORT=50001;SECURITY=SSL;UID=db2inst1;PWD=dbpwd;SSLServerCertificate=/home/db2inst1/db2_ssl/db2_ssl_keydb.arm;", "", "")

sql = "SELECT QUOTEID,GEO FROM DB2INST1.TRN fetch first 10 rows only with ur"

stmt = ibm_db.exec_immediate(conn, sql)

dictionary = ibm_db.fetch_both(stmt)

while dictionary != False:

print(dictionary["QUOTEID"])

print(dictionary["GEO"])

dictionary = ibm_db.fetch_both(stmt)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值