简体   繁体   English

使用 Python 连接到 db2 数据库

[英]Connect to db2 database with Python

I'm working on an app that needs to connect to an ibm db2 database.我正在开发一个需要连接到 ibm db2 数据库的应用程序。 Using DBeaver I can successfully connect to the database (I provide him the db2cc.jar and db2cc4.jar files).使用 DBeaver 我可以成功连接到数据库(我向他提供了db2cc.jardb2cc4.jar文件)。

It looks to me as DBeaver is using my Window's credentials to login, because I didn't need to input any login or password to connect.在我看来,DBeaver 正在使用我的 Window 凭据登录,因为我不需要输入任何登录名或密码来连接。

Now, I've been trying to connect to the same database using python 3.7 and pypi's latest version of the ibm_db package.现在,我一直在尝试使用 python 3.7 和 pypi 最新版本的ibm_db包连接到同一个数据库。 I didn't install anything else.我没有安装其他任何东西。

import ibm_db

# ...
connection_string = "DATABASE=" + self.params['schema'] + ";" + \
                                         "HOSTNAME=" + self.params['host'] + ";" + \
                                         "PORT=" + self.params['port'] + ";" + \
                                         "PROTOCOL=TCPIP;" + \
                                         "SECURITYMECHANISM=4;" + \
                                         "UID=" + self.params['user'] + ";" + \
                                         "PWD=" + self.params['password'] + ";"


try:
    self.connection = ibm_db.connect(connection_string, "", "")
    # ...

Using my Windows credentials in the parameters, I get the following error message:在参数中使用我的 Windows 凭据,我收到以下错误消息:

Connection error
Bad credentials
SQLCODE=-30082
08001

From what I've seen on stack overflow connecting to a db2 database is complicated...从我所看到的堆栈溢出连接到 db2 数据库是复杂的......

Does someone know how to connect ?有人知道怎么连接吗? Using the windows credentials or otherwise...使用 Windows 凭据或其他方式...

Thanks !谢谢 !

Try the following connection string, If your db2 client and server are on the same host.尝试以下连接字符串,如果您的 db2 客户端和服务器在同一主机上。 Change the 'mydb' and 'DB2' (db2 instance name, you can get it with db2ilist utility) constants according your case.根据您的情况更改“mydb”和“DB2”(db2 实例名称,您可以使用 db2ilist 实用程序获取它)常量。

ibm_db.connect('DATABASE=mydb;Instance=DB2;PROTOCOL=IPC;', '', '')

Db2 works fine with Python. Db2 与 Python 配合良好。

You need to be aware of some basics before you start such as:在开始之前,您需要了解一些基础知识,例如:

  • what operating-system runs the target Db2-database and运行目标 Db2 数据库的操作系统和
  • what kind of client is being used (java, odbc/cli, .net etc), and正在使用哪种客户端(java、odbc/cli、.net 等),以及
  • what kind of authentication/encrpytion is in place for the database (ssl, server based authentication/+/-/encryption etc.).数据库采用了哪种身份验证/加密(ssl、基于服务器的身份验证/+/-/加密等)。
  • is the remote database rdbms Apache DERBY or Db2.是远程数据库 rdbms Apache DERBY 或 Db2。

Find out these basics before you start.在开始之前先了解这些基础知识。 You have to speak with people who run the Db2-server.您必须与运行 Db2-server 的人交谈。

Note: in your question you mention ( SecurityMechanism=4 ) com.ibm.db2.jcc.DB2BaseDataSource.USER_ONLY_SECURITY - this is not relevant for non-JAVA clients, it is relevant is the database manager is DERBY .注意:在您的问题中,您提到 ( SecurityMechanism=4 ) com.ibm.db2.jcc.DB2BaseDataSource.USER_ONLY_SECURITY - 这与非 JAVA 客户端无关,相关的是数据库管理器是 DERBY 。

For python, the ibm_db package is not a java application.对于python,ibm_db 包不是java 应用程序。

DBeaver is a java application (hence it uses db2jcc.jar or db2jcc4.jar and a licence-file to connect to the remote database). DBeaver 是一个 Java 应用程序(因此它使用 db2jcc.jar 或 db2jcc4.jar 和一个许可证文件来连接到远程数据库)。

You can only use your Windows credentials for connecting to a Db2-database when that Db2-database run on Microsoft-Windows, and the credentials work on the hostname running the Db2-server.当 Db2 数据库在 Microsoft-Windows 上运行时,您只能使用 Windows 凭据连接到 Db2 数据库,并且凭据在运行 Db2 服务器的主机名上工作。 For any other combinations, the administrator must issue you a userid/password that is relevant for the target hostname.对于任何其他组合,管理员必须为您提供与目标主机名相关的用户 ID/密码。

The ibm_db package needs a Db2-client to be installed. ibm_db 包需要安装 Db2 客户端。 The Db2-client is a separate installable. Db2 客户端是可单独安装的。 There are different kinds of Db2-client depending both on which operating-system runs your Db2-server and how much functionality you need to have in your Db2-client.根据运行 Db2 服务器的操作系统以及需要在 Db2 客户端中拥有多少功能,有不同类型的 Db2 客户端。 If your remote Db2-server runs on Linux, Unix, Windows or Z/OS then you can use the "IBM Data Server Runtime Client" which you can either download from IBM's passport advantage website, or get from your internal IT folks.如果您的远程 Db2 服务器在 Linux、Unix、Windows 或 Z/OS 上运行,那么您可以使用“IBM Data Server Runtime Client”,您可以从 IBM 的通行证优势网站下载,或者从您的内部 IT 人员那里获取。 If your Db2-server runs on i-Series (AS/400) you should get its drivers from your i-Series administrator.如果您的 Db2 服务器在 i 系列 (AS/400) 上运行,您应该从 i 系列管理员那里获取其驱动程序。 For either Z/OS or i-Series you will additionally need a license file (which costs money) and you should get that from your administrator, unless your company uses a gateway product called Db2-connect in which case you don't need a separate license file on your workstation.对于 Z/OS 或 i 系列,您还需要一个许可证文件(需要花钱),您应该从管理员那里获得该文件,除非您的公司使用名为 Db2-connect 的网关产品,在这种情况下您不需要工作站上的单独许可证文件。

add ibm_db library and import ibm_db on top in the .py file.添加ibm_db库并在 .py 文件的顶部导入 ibm_db。

def get_db_connection():
    """
This will help to get db2 connection for query execution
    :return: conn
    """
    dsn_driver = "{IBM DB2 ODBC DRIVER}"
    dsn_database = "BLUDB"
    dsn_hostname = "your_hostname"
    dsn_port = "50000"
    dsn_protocol = "TCPIP"
    dsn_uid = "your_userid"
    dsn_pwd = "your_pwd"
    dsn = (
        "DRIVER={0};"
        "DATABASE={1};"
        "HOSTNAME={2};"
        "PORT={3};"
        "PROTOCOL={4};"
        "UID={5};"
        "PWD={6};").format(dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid, dsn_pwd)
    try:
        conn = ibm_db.connect(dsn, "", "")
        print("Connected!")
        return conn
    except Exception:
        print("\nERROR: Unable to connect to the \'" + dsn_database + "\' server.")
        print("error: ", ibm_db.conn_errormsg())
        exit(-1)

function get_db_connection() will return the connection object.函数 get_db_connection() 将返回连接对象。 On that connection object you can perform operation like:在该连接对象上,您可以执行如下操作:

conn = get_db_connection()
list_results = []
select_query = 'SELECT  a.STATUS,  a.ID  FROM  "TABLE_NAME" AS a'
print(select_query)
selectStmt = ibm_db.exec_immediate(conn, select_query)
while ibm_db.fetch_row(selectStmt) != False:
    list_results.append(ibm_db.result(selectStmt, 'ID'))
ibm_db.close(conn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM