有没有办法将Python连接到Db2?
解决方法:
文档很难找到,一旦你找到它,它就非常糟糕.这是我在过去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))
现在,行包含数据库中第170个表的行列表,其中每行包含列名称的值:value.
希望这一切都有帮助.