如何将Python连接到Db2

46 投票
14 回答
122588 浏览
提问于 2025-04-16 17:52

有没有办法把Python和Db2连接起来?

14 个回答

11

ibm-db是官方的DB2数据库驱动,适用于Python和Django,大家可以在这里找到:

这里有一个最近的教程,教你如何在Ubuntu Linux上安装所有东西:

我还要提一下,之前有几个旧的非官方的DB2驱动可以用在Python上,但ibm-db是你应该使用的那个。

17

经过一番研究,我发现了如何使用 ibm_db 连接到 DB2 数据库。

首先,如果你使用的 Python 版本高于 3.2,请使用:

pip install ibm_db==2.0.8a

因为最新的 2.0.8 版本会安装失败。

然后可以使用以下代码来连接:

import ibm_db_dbi as db

conn = db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;PWD=password;", "", "")

要列出表格,可以使用:

for t in conn.tables():
    print(t)

要执行 SQL 语句,可以使用:

cursor = conn.cursor()
cursor.execute("SELECT * FROM Schema.Table")
for r in cursor.fetchall():
    print(r)

你可以查看 这个链接,里面有官方的文档,不过可能不是特别准确。

37

文档很难找到,而且找到后也很糟糕。以下是我在过去3小时里发现的内容。

你需要通过 pip 安装 ibm_db,具体方法如下:

pip install ibm_db

接下来,你需要创建一个连接对象。文档在这里。

这是我写的代码:

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个表的行数据,每一行都是一个包含列名和对应值的 dict

希望这些信息对你有帮助。

撰写回答