LoginSignup
0
0

More than 1 year has passed since last update.

Db2 on IBM Cloud に Pythonからつなぐ(Select編)

Posted at

初めに

以前の投稿で、「IBM Cloud でDb2インスタンスを作成し、 Node.jsからアクセスしてみよう」という投稿をし、IBM Cloud のDb2を使用したと記載しましたが、今回は、Node.jsではなくPython(version3)での使用方法をご紹介します。

IBM CloudでのDb2の作成の仕方は、以前の投稿をご参照ください。

手順

1. ibm_dbモジュールのインストール

$ pip3 install ibm_db

※環境によってはpip3ではなく、pipの場合もあります。

2. ソースファイルの作成

ソースの中身はコメント行を参考にしてください。

select_db2.py
import ibm_db;

# db2接続情報の定義(xxxxxは環境に応じて書き換えてください)
db_con_str = \
"DRIVER={DB2}" \
  + ";DATABASE=" + "xxxxx" \
  + ";HOSTNAME=" + "xxxxx" \
  + ";PORT=" + "xxxxx" \
  + ";PROTOCOL=TCPIP" \
  + ";UID=" + "xxxxx" \
  + ";PWD=" + "xxxxx" \
  + ";Security=SSL"

# 実行するselect文を定義
sql_str = "SELECT EMPLOYEEID, NAME, SYSTOOLS.BSON2JSON(PROFILE) as PROFILE FROM EMPLOYEES;"

# db2接続情報から接続オブジェクトを生成
conn = ibm_db.connect(db_con_str,"","")

# 接続オブジェクトと実行SQL文より、statementオブジェクトを作成
stmt = ibm_db.exec_immediate(conn, sql_str)

# fetch_assocによって、1行分のデータが取得される。
dictionary = ibm_db.fetch_assoc(stmt)

# 全行分取得が終わるまで、fetch_assocで、順次1行ずつ読み取って、出力する。
while dictionary != False:
    print(dictionary)
    dictionary = ibm_db.fetch_assoc(stmt)

3. ソースファイルの実行

$ python3 select_db2.py
{'EMPLOYEEID': 100, 'NAME': 'Tom', 'PROFILE': '{"hobby":"baseball","license":"driver"}'}
{'EMPLOYEEID': 110, 'NAME': 'Jhon', 'PROFILE': '{"hobby":"football"}'}

※環境によってはpython3ではなく、pythonの場合もあります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0