K
K
Kotar4ik2021-04-24 13:38:45
Python
Kotar4ik, 2021-04-24 13:38:45

How to connect to an IBM DB2 database in Python?

Good afternoon.

Please help me with connecting to a database in Python.

I tried several options through various libraries, but it does not work.

1 option:

import jaydebeapi

connect = jaydebeapi.connect(
    'com.ibm.as400.access.AS400JDBCDriver', 
    'jdbc:as400://hostname.com;libraries=database_name;',['user','password'], 
    'Driver\jt400.jar')

curs = connect.cursor()
test = "SELECT 'Hello World!' AS Message FROM SYSIBM.SYSDUMMY1"

curs.execute(test)
curs.fetchall()


curs.close()
connect.close())


In it, at first glance, it seems that the connection was successful, but with curs.fetchall nothing is displayed in the console (even an error). The same SELECT through DBeaver works fine.

Option 2:
import ibm_db as ibm
classpath='Driver\jt400.jar'

ibm.connect(
        "DRIVER={{com.ibm.as400.access.AS400JDBCDriver}};"
        "DATABASE=DATABASE;"
        "HOSTNAME=HOSTNAME.COM;"
        "PORT=446;"
        "PROTOCOL=TCPIP;"
        "UID=user;"
        "PWD=password;",
        "", "")


In this case, even the connection does not occur. Gives an error message:
SQLCODE=-30061][CLI Driver] SQL30061N  The database alias or database name "DATABASE             " was not found at the remote node.  SQLSTATE=08004


3 option:

from py4j.java_gateway import JavaGateway

user = "user";
password = "password";
jdbc_url = "jdbc:as400://hostname.com;libraries=DATABASE;"


# Open JVM interface with the JDBC Jar
jdbc_jar_path = 'Driver\jt400.jar'
gateway = JavaGateway.launch_gateway(classpath='Driver\jt400.jar') 
jvm = gateway.jvm

# Load the JDBC Jar
jdbc_class = "com.ibm.as400.access.AS400JDBCDriver"
jvm.Class.forName(jdbc_class)

# Initiate connection

con =  jvm.DriverManager.getConnection(jdbc_url, user, password)


In this case, it gives an error:
TypeError: 'JavaPackage' object is not callable

Please help me to implement a connection to the database using Python. I've googled everything, can't seem to get it done.

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alexbprofit, 2021-04-24
@alexbprofit

and what for to db2?

V
Vasily Bannikov, 2021-04-24
@vabka

https://stackoverflow.com/questions/6044326/how-to...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question