How to connect Python to Db2

前端 未结 10 519
小鲜肉
小鲜肉 2020-12-04 19:53

Is there a way to connect Python to Db2?

相关标签:
10条回答
  • 2020-12-04 20:13

    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)
    
    0 讨论(0)
  • 2020-12-04 20:15

    There is a way in which one can connect to IBM db2 using nothing but Python requests library.
    Have a look at the following video, found it quite useful:
    https://youtu.be/PSNBDwgf9ts
    You need nothing but the requests library and your db2 credentials. Worked for me.

    0 讨论(0)
  • 2020-12-04 20:16

    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)
    
    0 讨论(0)
  • 2020-12-04 20:16

    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;", "", "")
    
    0 讨论(0)
提交回复
热议问题