如何连接python到db2
IBM-DB,Python和Django的官方DB2驱动程序是在这里:
下面是如何在Ubuntu Linux安装所有最近教程:
我应该提到,有几个较老的非官方DB2 for Python驱动程序。 ibm-db是你应该使用的那个。
您可以使用ibm_db库来连接DB2。
query_str = "SELECT COUNT(*) FROM table_name"
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt)
该文档很难找到,一旦你找到它,它是相当糟糕。这是我在过去3个小时里发现的。
你需要使用pip
安装ibm_db
,如下所示:
pip install ibm_db
你要创建一个连接对象。 The documentation is here.
这是我写的:
from ibm_db import connect
# Careful with the punctuation here - we have 3 arguments.
# The first is a big string with semicolons in it.
# (Strings separated by only whitespace, newlines included,
# are automatically joined together, in case you didn't know.)
# The last two are emptry strings.
connection = connect('DATABASE=<database name>;'
'HOSTNAME=<database ip>;' # 127.0.0.1 or localhost works if it's local
'PORT=<database port>;'
'PROTOCOL=TCPIP;'
'UID=<database username>;'
'PWD=<username password>;', '', '')
接下来,你应该知道,命令ibm_db
从来没有真正给你的结果。相反,您需要重复调用命令中的fetch
方法之一来获取结果。我写了这个帮助函数来处理这个问题。
def results(command):
from ibm_db import fetch_assoc
ret = []
result = fetch_assoc(command)
while result:
# This builds a list in memory. Theoretically, if there's a lot of rows,
# we could run out of memory. In practice, I've never had that happen.
# If it's ever a problem, you could use
# yield result
# Then this function would become a generator. You lose the ability to access
# results by index or slice them or whatever, but you retain
# the ability to iterate on them.
ret.append(result)
result = fetch_assoc(command)
return ret # Ditch this line if you choose to use a generator.
现在与辅助函数定义,你可以很容易地这样做有以下得到的所有表中的信息在数据库:
from ibm_db import tables
t = results(tables(connection))
如果你想看到的一切一个给定的表,你现在能做这样的事情:
from ibm_db import exec_immediate
sql = 'LIST * FROM ' + t[170]['TABLE_NAME'] # Using our list of tables t from before...
rows = results(exec_immediate(connection, sql))
现在rows
包含从第170表行的list
在你的数据库,其中e非常行包含列名称:值的dict
。
希望这一切都有助于。
我得到SQLCODE = -104的行: rows = results(exec_immediate(connection,sql)) 任何想法是什么导致这个错误? – crh878 2016-07-19 21:38:20
@ crh878 - [IBM DB2文档中说“SQLCODE = -104”表示您有一个非法的符号或标记。](http://www.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/codes/src/tpc /n104.html)我建议你在前面打印(sql)',然后复制并粘贴输出到另一个注释中,如果你看不到自己的错误。 – ArtOfWarfare 2016-07-20 03:08:12
是不是应该是这样的: sql ='SELECT * FROM'+ t [170] ['TABLE_NAME'] – ifelsemonkey 2016-12-07 09:35:29
这是供将来参考:
的Python 2.5或更高版本,不包括Python的3.x的
pip install ibm_db
它只是工作在Python 2里。7对我来说;它不适用于3.X.此外,我必须使Python 2.7默认(而不是Python 3),以便安装工作(否则,会有安装错误)。
import ibm_db
ibm_db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username; PWD=password;", "", "")
我们怎样的'ibm_db'库? – ArtOfWarfare 2016-02-03 15:18:19
@ArtOfWarfare,只需导入它。 'pip install ibm_db' – 2016-09-07 07:29:53