如何将 Python 连接到 Db2

发布于 2024-11-08 04:51:38 字数 26 浏览 2 评论 0 原文

有没有办法将Python连接到Db2?

Is there a way to connect Python to Db2?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

雨夜星沙 2024-11-15 04:51:38

该文档很难找到,一旦找到,就会发现它非常糟糕。这是我在过去 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

希望这一切都有帮助。

The documentation is difficult to find, and once you find it, it's pretty abysmal. Here's what I've found over the past 3 hours.

You need to install ibm_db using pip, as follows:

pip install ibm_db

You'll want to create a connection object. The documentation is here.

Here's what I wrote:

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>;', '', '')

Next you should know that commands to ibm_db never actually give you results. Instead, you need to call one of the fetch methods on the command, repeatedly, to get the results. I wrote this helper function to deal with that.

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.

Now with that helper function defined, you can easily do something like get the information on all the tables in your database with the following:

from ibm_db import tables

t = results(tables(connection))

If you'd like to see everything in a given table, you could do something like this now:

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))

And now rows contains a list of rows from the 170th table in your database, where every row contains a dict of column name: value.

Hope this all helps.

2024-11-15 04:51:38

经过大量挖掘,我发现了如何使用 ibm_db 连接 DB2。

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

pip 安装 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)

并通过检查 此链接 官方不太准确的文档

After lots of digging I discovered how to connect with DB2 using ibm_db.

First off, if you use a python version higher than 3.2 use

pip install ibm_db==2.0.8a

version 2.0.8 (the latest) will fail to install.

then use the following to connect

import ibm_db_dbi as db

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

list tables with

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

and execute SQL with

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

check this link for official not so accurate documentation

爱你是孤单的心事 2024-11-15 04:51:38

ibm-db,Python 和 Django 的官方 DB2 驱动程序位于:

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

我应该提到的是,有几个较旧的非官方 DB2 驱动程序对于Python。 ibm-db 是您应该使用的。

ibm-db, the official DB2 driver for Python and Django is here:

Here's a recent tutorial for how to install everything on Ubuntu Linux:

I should mention that there were several older unofficial DB2 drivers for Python. ibm-db is the one you should be using.

亣腦蒛氧 2024-11-15 04:51:38

除了 @prof1990 响应

自 2.0.9(2018 年 8 月 16 日)以来,对于 Python 3,您也可以简单地使用:

pip install ibm_db

参考:

https://github.com/ibmdb/python-ibmdb#updated-ibm_db

连接示例 此处

import ibm_db
ibm_db.connect("DATABASE=<dbname>;HOSTNAME=<host>;PORT=<60000>;PROTOCOL=TCPIP;UID=<username>;PWD=<password>;", "", "")

完整的 API 文档位于此处:

https://github.com/ibmdb/python-ibmdb/wiki/APIs

In addition to @prof1990 response:

Since 2.0.9 (Aug 16th 2018), also with Python 3 you can simply use:

pip install ibm_db

Reference:

https://github.com/ibmdb/python-ibmdb#updated-ibm_db

Example of connection here:

import ibm_db
ibm_db.connect("DATABASE=<dbname>;HOSTNAME=<host>;PORT=<60000>;PROTOCOL=TCPIP;UID=<username>;PWD=<password>;", "", "")

Full API documentation here:

https://github.com/ibmdb/python-ibmdb/wiki/APIs

开始看清了 2024-11-15 04:51:38

您可以使用 jaydeapi 从 python 连接到 db2
首先运行 pip install jaydeapi 安装库
下载 db2jcc4.jar
然后您可以使用以下代码进行连接:
通过传递主机名、端口号、用户 ID、密码数据库名称

import jaydebeapi

conn_src = jaydebeapi.connect(
    'com.ibm.db2.jcc.DB2Driver',
    ['YourHostName:PortNo/DatabaseName','userid','password'],'C:/db2jcc4.jar'
)

cursor=conn_src.cursor()
sql = 'Select * from schemaname.TableName fetch first 100 rows only '

cursor.execute(sql)
print("fetchall:")
result = cursor.fetchall()
for r in result:
    print(r)

You can connect to db2 from python using jaydeapi
First install library running pip install jaydeapi
download db2jcc4.jar
Then you can connect using below code :
by passing hostname,portno, userid,password database name

import jaydebeapi

conn_src = jaydebeapi.connect(
    'com.ibm.db2.jcc.DB2Driver',
    ['YourHostName:PortNo/DatabaseName','userid','password'],'C:/db2jcc4.jar'
)

cursor=conn_src.cursor()
sql = 'Select * from schemaname.TableName fetch first 100 rows only '

cursor.execute(sql)
print("fetchall:")
result = cursor.fetchall()
for r in result:
    print(r)
浪推晚风 2024-11-15 04:51:38

有一种方法可以只使用 Python 请求库来连接到 IBM db2。为我工作。

第 1 步:
转至 IBM CLOUD 仪表板 ->导航到您的 IBM db2 实例 ->点击“服务凭证”
应该有一个默认的,如果没有,请创建一个。该服务凭证是一本字典。复制服务凭据。

第 2 步:

db2id = { // service credential dictionary here //}
api = "/dbapi/v3"
host = db2id['https_url']+api
userinfo = {"userid":db2id['username'],"password":db2id['password']}
service = '/auth/tokens'
r = requests.post(host+service,json=userinfo)
access_token = r.json()['token']
auth_header = {"Authorization": "Bearer "+access_token}

// Connection to database established

第 3 步
现在您可以运行 SELECT、INSERT、DELETE、UPDATE 查询
INSERT、DELETE、UPDATE 查询的格式是相同的。在 INSERT、DELETE、UPDATE 查询之后,必须发送 COMMIT 查询,否则不会反映更改。 (否则您也应该提交更改)

插入/更新/删除查询

sql = " your insert/update/delete query here "
sql_command = {"commands":sql,"limit":1000,"separator":";","stop_on_error":"yes"}
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)
sql_command = {"commands":"COMMIT","limit":1000,"separator":";","stop_on_error":"yes"}
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)

您可以使用变量 r 来检查请求的状态

SELECT QUERIES

sql = " your select query here "
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)
jobid = r.json()['id']
r = requests.get(host+service+"/"+jobid,headers=auth_header)
results = r.json()['results']
rows = results[0]['rows']

变量rows 将包含您的查询结果。根据您的方便使用它。

我没有使用任何 DDL 查询。但我认为它们应该像 DML 查询一样工作。但不确定!

There is a way in which one can connect to IBM db2 using nothing but Python requests library. Worked for me.

STEP 1:
Go to IBM CLOUD Dashboard -> Navigate to your IBM db2 instance -> Click on 'Service Credentials'
A default one should be there, if not, create one. This service credential is a dictionary. Copy the service credentials.

STEP 2:

db2id = { // service credential dictionary here //}
api = "/dbapi/v3"
host = db2id['https_url']+api
userinfo = {"userid":db2id['username'],"password":db2id['password']}
service = '/auth/tokens'
r = requests.post(host+service,json=userinfo)
access_token = r.json()['token']
auth_header = {"Authorization": "Bearer "+access_token}

// Connection to database established

STEP 3
Now you can run SELECT, INSERT, DELETE, UPDATE queries
The format for INSERT, DELETE, UPDATE queries is the same. After an INSERT, DELETE, UPDATE query, a COMMIT query has to be sent, else changes aren't reflected. (You should commit your changes otherwise also)

INSERT / UPDATE / DELETE QUERIES

sql = " your insert/update/delete query here "
sql_command = {"commands":sql,"limit":1000,"separator":";","stop_on_error":"yes"}
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)
sql_command = {"commands":"COMMIT","limit":1000,"separator":";","stop_on_error":"yes"}
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)

You can use the variable r to check status of your request

SELECT QUERIES

sql = " your select query here "
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)
jobid = r.json()['id']
r = requests.get(host+service+"/"+jobid,headers=auth_header)
results = r.json()['results']
rows = results[0]['rows']

The variable rows will have the results of your query. Use it as per your convenience.

I didn't use any DDL queries. But I think they should work like the DML queries. Not sure though!

如此安好 2024-11-15 04:51:38

IBM 的 Db2 可用于各种平台。如果您尝试连接到位于 IBM i 服务器(以前称为 AS/400、iSeries 或 System i)上的 Db2,则 ibm_db 需要名为 Db2 Connect,相当昂贵。大多数使用 Python 连接到 Db2 的人都使用 ODBC(通常通过 PyODBC)。

我不完全确定他们的 z(大型机)服务器上的 Db2 的情况,但我认为它也需要 Db2 Connect。

IBM's Db2 is available for various platforms. If you are trying to connect to a Db2 which lives on an IBM i server (formerly known as AS/400, iSeries, or System i), then ibm_db requires a product called Db2 Connect, which is rather expensive. Most people who use Python to connect to Db2 for i use ODBC (usually through PyODBC).

I'm not completely sure about the situation with Db2 on their z (mainframe) servers, but I would think it also requires Db2 Connect.

安穩 2024-11-15 04:51:38

从 Python 连接到 Db2 有多种方法。我试图提供选项的摘要。请注意,在许多环境中,现在强制执行 SSL/TLS,这需要额外的参数(见下文)。

Db2 和 Python 驱动程序

Db2 不提供一种,而是四种用于 Python 的驱动程序(客户端)。 Db2 文档页面“Python、SQLAlchemy ,以及 IBM 数据库服务器的 Django 框架应用程序开发” 提供了有关这四个驱动程序的良好概述:

请注意,还有其他 Python 数据库接口,它们利用现有的 JDBC 或 ODBC 驱动程序,可用于连接到 Db2。您可以将 SQLAlchemy (ibm_db_sa) 与流行的 Flask 框架 结合使用。要将 Db2 与 pandas 结合使用,请使用 ibm_db_dbi。上述所有Db2 驱动程序均可在 GitHub 上获取,并且均基于 CLI(调用级接口/ODBC) 。还有其他方法可以连接到 Db2,例如,使用基于 ODBC 的第 3 方包装器等。

Db2 连接

典型的连接信息由 Db2 服务器(主机名)、端口、数据库名称和用户名/密码信息组成。如果未指定任何其他内容,大多数驱动程序会假定连接未加密。因此,要通过加密连接进行连接,需要更多参数。它们取决于 Db2 版本、Db2 产品的类型等等。让我们从简单的开始吧。

较新的 Db2 版本简化了 SSL/TLS 的使用,因为证书现在是包的一部分。典型的连接字符串将如下所示:

conn_str='database=MYDB;hostname=db2host.example.com;port=50001;protocol=tcpip;uid=db2inst1;pwd=secret;security=SSL'

ibm_db_conn = ibm_db.connect(conn_str,'','')

一个重要的参数是“security=SSL”,用于告诉驱动程序使用 对传输中的数据进行加密

Db2 连接字符串可以有更多选项。这取决于启用了哪些安全插件。请参阅此博客文章,了解 从 Python 连接访问 Db2 以获取更多链接和讨论。

SQL Alchemy 连接

将 Db2 与 SQLAlchemy 结合使用时,传递类似于

ibm_db_sa://user:password@hostname:port/database?Security=SSL 的 URI

以建立连接。

There are many ways to connect from Python to Db2. I am trying to provide a summary of options. Note that in many environments SSL/TLS is enforced now which requires additional parameters (see below).

Db2 and Python drivers

Db2 does not offer one, but four drivers (clients) for Python. The Db2 documentation page "Python, SQLAlchemy, and Django Framework application development for IBM Database servers" provides a good overview about the four drivers:

Note that there are additional Python database interfaces which make use of existing JDBC or ODBC drivers which can be used to connect to Db2. You can use SQLAlchemy (ibm_db_sa) with the popular Flask framework. To use Db2 with pandas utilize ibm_db_dbi. All of the above Db2 drivers are available on GitHub and are based on the CLI (Call Level Interface / ODBC). There are additional ways to connect to Db2, e.g., by using 3rd party ODBC-based wrappers and more.

Db2 connections

Typical connection information is made up of the Db2 server (hostname), the port, the database name and username / password information. If nothing else is specified, most drivers assume that the connection is not encrypted. Thus, to connect over an encrypted connection more parameters are needed. They depend on the Db2 version, the type of Db2 product and some more. Let's start easy.

Newer Db2 versions simplified the use of SSL/TLS because certificates are now part of the package. A typical connection string would then look like this:

conn_str='database=MYDB;hostname=db2host.example.com;port=50001;protocol=tcpip;uid=db2inst1;pwd=secret;security=SSL'

ibm_db_conn = ibm_db.connect(conn_str,'','')

An important parameter is "security=SSL" to tell the driver to use encryption for the data in transit.

Db2 connection strings can have even more options. It depends on what security plugin is enabled. See this blog post on connecting from Python to Db2 for more links and discussions.

SQL Alchemy connection

When using Db2 with SQLAlchemy, pass an URI similar to

ibm_db_sa://user:password@hostname:port/database?Security=SSL

to get the connection established.

心是晴朗的。 2024-11-15 04:51:38

这就是我如何从 Python 成功连接 IBM DB2 并检索结果。

问题:

当我尝试安装 pip install ibm-db 时,出现此错误:

pip install ibm-db
running build_ext
building 'ibm_db' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
  ----------------------------------------
ERROR: Failed building wheel for ibm-db
Failed to build ibm-db
ERROR: Could not build wheels for ibm-db, which is required to install pyproject.toml-based projects.

解决方案:

  1. 我从 https://python-forum.io/thread-38681.html

    G:\div_code\answer
    λ python -m venv ibm_env
    
    G:\div_code\answer
    λ cd ibm_env\
    
    G:\div_code\answer\ibm_env
    λ G:\div_code\answer\ibm_env\Scripts\activate
    
    (ibm_env) G:\div_code\answer\ibm_env
    pip 安装 ibm-db
    
  2. 我将以下文件夹/文件从 ibm_env\Lib\site-packages 复制到我安装的 Python Python36\Lib\site-packages

    <前><代码>ibm_db
    ibm_db_dbi
    证书(文件夹)
    clidriver(文件夹)
    ibm_db_dlls(文件夹)
    ibm_db_tests(文件夹)
    ibm_db-3.1.3-py3.6.egg-info(文件夹)

This is how I successfully connected IBM DB2 from Python and retrieved the results.

Issue:

When I tried to install pip install ibm-db, I got this error:

pip install ibm-db
running build_ext
building 'ibm_db' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
  ----------------------------------------
ERROR: Failed building wheel for ibm-db
Failed to build ibm-db
ERROR: Could not build wheels for ibm-db, which is required to install pyproject.toml-based projects.

Solution:

  1. I found the below steps from https://python-forum.io/thread-38681.html

    G:\div_code\answer
    λ python -m venv ibm_env
    
    G:\div_code\answer
    λ cd ibm_env\
    
    G:\div_code\answer\ibm_env
    λ G:\div_code\answer\ibm_env\Scripts\activate
    
    (ibm_env) G:\div_code\answer\ibm_env
    λ pip install ibm-db
    
  2. I copied the below folders/files from ibm_env\Lib\site-packages to my python installed Python36\Lib\site-packages

    ibm_db
    ibm_db_dbi
    certs (Folder)
    clidriver (Folder)
    ibm_db_dlls (Folder)
    ibm_db_tests (Folder)
    ibm_db-3.1.3-py3.6.egg-info (Folder)
    
南笙 2024-11-15 04:51:38

您可以使用 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)

You can use ibm_db library to connect 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)
圈圈圆圆圈圈 2024-11-15 04:51:38

这是供将来参考:

官方安装文档说:

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;", "", "")

This is for future reference:

Official installation docs say:

Python 2.5 or later, excluding Python 3.X.

pip install ibm_db

It only worked on Python 2.7 for me; it didn't for 3.X. Also, I had to make Python 2.7 default (instead of Python 3) so that the installation would work (otherwise, there would be installation errors).

Official docs sample usage:

import ibm_db 
ibm_db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username; PWD=password;", "", "")
灯角 2024-11-15 04:51:38

版本:ibm-db 3.0.2 - ibm-db==3.0.2

pip install ibm-db

发布时间:2020 年 6 月 17 日

连接到本地或编目数据库:

import ibm_db
conn = ibm_db.connect("database","username","password")

连接到未编目数据库:

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

Version: ibm-db 3.0.2 - ibm-db==3.0.2

pip install ibm-db

Released: Jun 17, 2020

Connect to a local or cataloged database:

import ibm_db
conn = ibm_db.connect("database","username","password")

Connect to an uncataloged database:

import ibm_db
ibm_db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;
            PWD=password;", "", "")
柠檬色的秋千 2024-11-15 04:51:38

2021 年我的表现如何。
您需要什么:

  • Python 3.7
  • PipEnv
  • Ibm-db

Ibm-db 版本并不重要,但该库仅适用于 Python 3.7(当前 python 版本是 3.9)。

在您的计算机中安装 Python 3.7.6(这是有效的版本)。

在 IDE 中创建一个新的 python 文件。

让我们创建一个虚拟环境,以确保我们将使用 Python 3.7

pip install pipenv

安装后

pipenv install --python 3.7

激活虚拟环境

pipenv shell

您可以使用 pip list 来验证您是否位于新的虚拟环境中 -如果列表仅显示 3 或 4 个库,那是因为您

现在可以下载 Ibm_db

pip install ibm-db

您可以将其添加到代码中以确认您使用的版本是什么

from platform import python_version
print(python_version())

现在访问 DB2强>

import ibm_db_dbi as db

# Connect to DB2B1 (keep Protocol as TCPIP)
conn = db.connect("DATABASE=DBNAME;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=Your User;PWD=Your Password;", "", "")

检查所有可用的表

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

您的SQL代码:

sql_for_df = """SELECT *
                FROM TABLE
                WHERE ..."""

可视化为DataFrame

首先安装pandas,因为它不会出现在您的虚拟环境中

pip install pandas

然后导入到您的代码并尝试

import pandas as pd 

df = pd.read_sql(sql_for_df, conn) 
df.head()

要退出虚拟环境只需编写< code>exit 在您的终端中。
如果您想删除虚拟环境,请在终端中写入 pipenv --rm

这几乎是迄今为止我能学到的全部内容。
希望对大家有所帮助。

How I managed to do in 2021.
What you will need:

  • Python 3.7
  • PipEnv
  • Ibm-db

Ibm-db version is not important but this lib only works with Python 3.7 (current python version is 3.9).

Install Python 3.7.6 in your machine (this is the version that worked).

In your IDE create a new python file.

Let' create a Virtual Enviroment to make sure we will use Python 3.7

pip install pipenv

After installing

pipenv install --python 3.7

Activate the Virtual Environment

pipenv shell

You can use pip list to verify if you are in the new Virtual Enviroment - if list only shows 3 or 4 libs, it's because you are

Now you can download Ibm_db

pip install ibm-db

You may add this to your code to confirm what is the version you are using

from platform import python_version
print(python_version())

Now accessing the DB2

import ibm_db_dbi as db

# Connect to DB2B1 (keep Protocol as TCPIP)
conn = db.connect("DATABASE=DBNAME;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=Your User;PWD=Your Password;", "", "")

Checking all tables available

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

Your SQL code:

sql_for_df = """SELECT *
                FROM TABLE
                WHERE ..."""

Visualizing as DataFrame

First install pandas as it will not be present in your Virtual Environment

pip install pandas

After that import to your code and play around

import pandas as pd 

df = pd.read_sql(sql_for_df, conn) 
df.head()

To exit the VIrtual Enviroment just write exit in your terminal.
If you want to remove the Virtual Enviroment write in the terminal pipenv --rm

That's pretty much all I could learn so far.
I hope it helps you all.

雪落纷纷 2024-11-15 04:51:38
# Install : ibm_db package
# Command : pip install ibm_db

import ibm_db
import sys


def get_connection():
    db_name = ""
    db_host_name = ""
    db_port = ""
    db_protocol = ""
    db_username = ""
    db_password = ""

    try:
        conn = ibm_db.connect(
        f"DATABASE = {db_name}; HOSTNAME = {db_host_name}; PORT = {db_port}; PROTOCOL = {db_protocol}; "
        f"UID = {db_username}; PWD = {db_password};", "", "")
        return conn
    except:
        print("no connection:", ibm_db.conn_errormsg())
        sys.exit(1)

get_connection()
# Install : ibm_db package
# Command : pip install ibm_db

import ibm_db
import sys


def get_connection():
    db_name = ""
    db_host_name = ""
    db_port = ""
    db_protocol = ""
    db_username = ""
    db_password = ""

    try:
        conn = ibm_db.connect(
        f"DATABASE = {db_name}; HOSTNAME = {db_host_name}; PORT = {db_port}; PROTOCOL = {db_protocol}; "
        f"UID = {db_username}; PWD = {db_password};", "", "")
        return conn
    except:
        print("no connection:", ibm_db.conn_errormsg())
        sys.exit(1)

get_connection()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文