Art*_*are 19

文档很难找到,一旦你找到它,它就非常糟糕.这是我在过去3小时内发现的.

您需要安装ibm_db使用pip,如下所示:

pip install ibm_db
Run Code Online (Sandbox Code Playgroud)

您将要创建一个连接对象.文档在这里.

这是我写的:

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>;', '', '')
Run Code Online (Sandbox Code Playgroud)

接下来你应该知道命令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.
Run Code Online (Sandbox Code Playgroud)

现在定义了这个辅助函数,您可以轻松地执行以下操作:获取有关数据库中所有表的信息:

from ibm_db import tables

t = results(tables(connection))
Run Code Online (Sandbox Code Playgroud)

如果您想要查看给定表中的所有内容,您现在可以执行以下操作:

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))
Run Code Online (Sandbox Code Playgroud)

现在rows包含list数据库中第170个表的一行,其中每行包含一个dict列名:value.

希望这一切都有帮助.


Leo*_*ons 10

ibm-db,Python和Django的官方DB2驱动程序在这里:

这是一个关于如何在Ubuntu Linux上安装所有内容的最新教程:

我应该提到有几个旧的非官方DB2驱动程序用于Python.ibm-db是你应该使用的那个.


小智 9

经过大量的研究,我发现了如何使用ibm_db与DB2连接。

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

点安装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;", "", "")
Run Code Online (Sandbox Code Playgroud)

列出表

for t in conn.tables():
    print(t)
Run Code Online (Sandbox Code Playgroud)

并执行SQL

cursor = conn.cursor()
cursor.execute("SELECT * FROM Schema.Table")
for r in cursor.fetchall():
    print(r)
Run Code Online (Sandbox Code Playgroud)

检查此链接以获得官方不太准确的文档

  • 老实说,我只是为了 2.0.8a 的提示而投票。我无法验证连接字符串,因为我没有 ibm_db 使用的驱动程序。我确实有一个适用于 pyodbc 的 ODBC 驱动程序,所以这就是我实际使用的。 (2认同)