How to use IBM_DB with older versions of DB2? - python

I want to connect Python to DB2 version 9.1 using IBM DB2 ODBC Driver.
Following is my code to connect Python to DB2. This program is working in the later versions of IBM DB2.
import ibm_db
conn = ibm_db.connect("DSN=PDB2;DRIVER={IBM DB2 ODBC DRIVER};DATABASE=MDBASIS;PORT=1234;PROTOCOL=TCPIP;UID=username;PWD=password","","")
stmt = ibm_db.exe_immediate(conn,"create table egg (ID SMALLINT, NAME VARCHAR(30))")
stmt = ibm_db.exe_immediate(conn,"insert into egg (ID, NAME) VALUES('1','ok')")
state = ibm_db.exe_immediate("select * from egg")
result = ibm_db.fetch_both(state)
while result != False:
print 'id = %d and name = %s' %(result[0],result[1])
result = ibm_db.fetch_both(state)
stmt = ibm_db.exe_immediate(conn,"drop table egg")
My problem is, the version of my IBM DB2 is 9.1 without FixPack and I get an error message when I try to connect to IBM DB2 9.1 version.
"[IBM][CLI Driver] CLI0133E Option type out of range. SQLSTATE=HY092 SQLCODE=-99999"
And the explanation for this error written in page http://programmingzen.com/2008/02/08/essential-guide-to-the-ruby-driver-for-db2/is:
"If you get this error, it usually means that you are using a version of DB2 that is too old. Install the latest FixPack or the latest version of DB2 (currently 9.5) to resolve the problem."
But I cannot install latest FixPack or the latest version of DB2 or in any way modify existing DB2 installation.
Question
Is there any way I can connect to DB2 version 9.1 without modifying the database, possibly using something else than IBM_DB?

I think the problem is in the client ibm_db driver. Basically you can connect to any older version from all the languages. Try to get another db2 driver. If I were you I would install the db2 client which comes with several drivers which are located in sqllib.

What version of ibm_db are you using? I am able to connect to DB2 9.1 with ibm_db 1.0.4 without problems.
Also: Based on the fact that you're specifying DSN in your connection string, I assume that you already have the database cataloged on the client as PDB2. You can greatly simply your connect statement to:
conn = ibm_db.connect('PDB2','username','password')
The only time you need to use the longer form (where you specify DATABASE/PORT/HOST/UID/PWD) is if you are using a DSN-less connection (i.e. the database has not been cataloged on the local machine).

I guess your DB2 client API version is higher than the DB2 server itself, ensure you use the same version on the client machine, try to connect and maintain your database remotely using the DB2 control center, and try to connect from python with:
conn = ibm_db.connect("MDBASIS", "username", "password")
AFAIK, this would force the wrapper to use native library instead of odbc.

ibm_db (and PyDB2 are just python modules that allow you to access the DB2 API calls through python. The DB2 queries themselves are being performed by your DB2 installation... something very separate from ibm_db and PyDB2.
It sounds like your DB2 installation is the problem, not ibm_db. You can test this by running db2 from the command line and seeing if you can execute your query directly in the db2 command line interface.

Related

Error connecting to local oracle database with cx_Oracle in Jupyter

I want to connect to local database with cx_Oracle but it throws an error:
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help
I can connect to database with sqlplus and SQL Developer, but it doesnt work with Python cx_Oracle in Jupyter.
import cx_Oracle
host = 'localhost'
port = 1521
SID = 'xe'
dsn_tns = cx_Oracle.makedsn(host, port, SID)
connection = cx_Oracle.connect('user', 'passwd', dsn_tns)
Is it possible I messed sth. with environment variables or client installation?
echo ${ORACLE_HOME};
/u01/app/oracle/product/11.2.0/xe
echo ${LD_LIBRARY_PATH};
/usr/lib/oracle/12.2/client64/lib
I installed client in /usr/lib/oracle/12.2/client64/lib
You may as well update cx_Oracle. The DPI-1047 message is using text that was updated in recent versions. This won't actually solve your problem
Keep it clean. Don't set ORACLE_HOME if you are using Oracle Instant Client.
I suspect your environment variables aren't being propagated down to cx_Oracle.
With a 64-bit XE, you shouldn't need to install Instant Client in your case (because your cx_Oracle message tells me it is 64-bit because the error is looking for a 64-bit Oracle client). cx_Oracle can use the DB libraries.
Once you sort out your library search path issue, you will then hit a problem with your connection string. You are trying to use an old SID construct, but should use a Service Name. It needs to be set like:
sn = 'xe'
dsn_tns = cx_Oracle.makedsn(host, port, service_name=sn)
The cx_Oracle documentation covers installation and also has a User Guide section that is worth reviewing https://cx-oracle.readthedocs.io/en/latest/index.html

pyodbc fails to connect to database, but IBM data studio connects with same credentials

I'm trying to connect to a database on an IBM machine, and I can connect just fine via the IBM desktop client "IBM Data Studio." However, when I try to connect with pyodbc it fails to connect. I've received a series of errors but it seems the main response is along the lines of the following
pyodbc.OperationalError: ('08001', u'[08001] [Microsoft][ODBC SQL Server Driver]
[TCP/IP Sockets]SQL Server does not exist or access denied. (17)
(SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]ConnectionOpen (
Connect()). (10061); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)')
My code follows:
import pyodbc
# Specifying the ODBC driver, server name, database, etc. directly
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=*****; PORT=50000;DATABASE=****;UID=***;PWD=***')
# Create a cursor from the connection
cursor = cnxn.cursor()
cnxn.close()
I am working on a Windows machine.
You cannot use an ODBC Driver for Microsoft SQL Server, to connect to an instance of IBM DB2 (nor to any DBMS other than Microsoft SQL Server).
You need an ODBC Driver for IBM DB2 for this connection, such as those from my employer.
You could also use an ODBC-to-JDBC Bridge Driver, in combination with a JDBC Driver for IBM DB2, such as JTOpen (open source, from IBM).
Just because a jdbc connection from Data-Studio is working, it does not mean that your pyodbc will connect to Db2. pyodbc does not use jdbc, instead it will use the CLI/ODBC interface to Db2 which gets implemented by a suitable driver.
To use Db2 from pyodbc on Windows, ensure you first have either a Db2-client installed on Windows, or a Db2-server installed installed on Windows.
There are many kinds of Db2-clients. Much depends on the operating-system that runs your Db2-server (Z/OS, i-Series, Linux, Unix, Windows), and what kind of activities you want to perform on the client (developing, administering/monitoring, querying, or all three).
For some target platforms there are non-IBM drivers, but I won't discuss those.
In python, you can choose to connect to a database either with a DSN (Data Source Name) (usually this involves a shorter connection string)
or without a DSN (longer connection string containing all the details).
When learning, it may be easier to get Microsoft Windows to do most of the initial work with odbcad32.
This is most easy if the Db2-client is already configured to access one or more Db2-databases . The prereq is that the driver supports CLI/ODBC.
To define a DSN (either a system-DSN or a user-DSN) use the Microsoft odbcad32 tool to point to your Db2 database and verify connectivity.
If the Db2-server runs on Z/OS or i-Series, special licensing requirements may apply depending on whether you are directly connecting to the target Db2-server or whether you are using a Db2-connect gateway.
Take a note of the exact DRIVER string inside odbcad32 for the Db2-database, including case and spaces because you will need that in your python code.
For example, that driver name might look like 'IBM DB2ODBC DRIVER - DB2COPY1' if you have a local Db2-server installed on Windows (such as the free Db2-Express-C).
Verify that the connection to the Db2-database is successful inside odbcad32. That is crucial.
When odbcad32 succeeds to connect then pyodbc will succeed to connect usually.
In your python code, your connection-string can either use the DSN or explicitly quote the DRIVER/SERVER/PORT/DATABASE/UID/PWD, along with any other required settings on the connection string.
Remember also that you don't have to use pyodbc. There are other options for python to interact with Db2-Servers. Make an informed choice and do your research.
You can also use the IBM supplied module "ibm_db" or the DBI interface module "ibm_db_api", or if you are using an object relational mapper you can use the SQLAlchemy adapter (ibm_db_sa), or you can use django framework.
Read all about that in the Db2 documentation here.
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_10.5.0/com.ibm.swg.im.dbclient.python.doc/doc/c0054366.html
I have solved the problem! The issue was that I was missing the "iSeries Access ODBC Driver". I don't think it's available online, although I could be wrong, I had to have our database guy help install it. Now I can connect through both the ibm_db and pyodbc libraries, after setting up my DSN under "odbcad32.exe." This took a while to solve but mostly because of the lack of informative documentation from IBM. Hopefully, this helps anyone in the same situation.

error when connecting oracle in python using cx_Oracle

I was trying to connect oracle database using python like below.
import cx_Oracle
conn = cx_Oracle.connect('user/password#host:port/database')
I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help.
I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,
'admin/admin#10.10.10.10:1010/orcl'.
Why coudn't it connect?
Ahh, btw I'm running all the code in azure notebooks.
That error indicates that you are missing a 64-bit Oracle client installation or it hasn't been configured correctly. Take a look at the link mentioned in the error message. It will give instructions on how to perform the Oracle client installation and configuration.
[Update on behalf of Anthony: his latest cx_Oracle release doesn't need Oracle Client libraries so you won't see the DPI-1047 error if you upgrade. The driver got renamed to python-oracledb but the API still supports the Python DB API 2.0 specification. See the homepage.]
This seems a problem with version 6.X.This problem didnot appeared in 5.X.But for my case a little workaround worked.I installed in my physical machine and only thing that i need to do was a pc reboot or reopen the terminal as i have added in the path of environment variables.You can try to install in physical machine instead using azure notebooks.
This error come when your Oracle Client is not installed or LD_LIBRARY_PATH is not set where libclntsh.so is present.
if you have Oracle client installed then search for libclntsh.so and set the LD_LIBRARY_PATH as
"export LD_LIBRARY_PATH=/app/bds/parcels/ORACLE_INSTANT_CLIENT/instantclient_11_2:$LD_LIBRARY_PATH"
Here is the full program to connect Oracle using python.
First, you need to install cx_Oracle. to install it fire the below command.
pip install cx_Oracle
import cx_Oracle
def get_databse_coonection():
try:
host='hostName'
port ='portnumber'
serviceName='sid of you database'
user = 'userName'
password = 'password'
dns = cx_Oracle.makedsn(host,port,service_name=serviceName)
con = cx_Oracle.connect(user, password, dns)
cursor = con.cursor()
query ="select * from table"
cursor.execute(query)
for c in cursor:
print(c)
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
finally:
if cursor:
cursor.close()
if con:
con.close()
get_databse_coonection()

which version of MySQL driver to use in Pyodbc

I am trying to connect to MYSQl db Server using pyodbc module.
with pyodbc.connect('DRIVER={MySQL ODBC 5.6 Driver};SERVER=XX.XX.X.XX;PORT=3306;DATABASE=ssc;UID=Pra;PASSWORD=welcome;') as cnxn:
cursor = cnxn.cursor()
cursor.execute('insert into ....')
When I ran the above code in python I am encountering an error 'local variable 'cnxn' referenced before assignment'I am working on MySQL workbench 6.2 and I am not sure which version of MySQL driver to use.
This specific error isn't a problem with the driver, the cnxn object is never created.
Change your code to:
cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.6 Driver};SERVER=XX.XX.X.XX;PORT=3306;DATABASE=ssc;UID=Pra;PASSWORD=welcome;')
cursor = cnxn.cursor()
cursor.execute('insert into ....')
The pyodbc wiki has a getting started section that is helpful.
For further reading, see pyodbc issue 100 concerning use of with.
Why don't you try using the MySQL driver for Python?
pip install MySQL-python

Python 3.2 script to connect to local MySQL database

I am running an Ubuntu Server. I would like for it to have a Python (v3.2) CGI script that would connect, and run a query, to the local MySQL database I have set up. Currently, the only things I found don't support Python 3.2. Please do not suggest switching to an earlier version of Python, because that is not an option for me.
pymysql - Pure Python MySQL client is very good.
It works with Python 3.x, and doesn't have any dependencies.
This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.
Example:
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
print(r)
cur.close()
conn.close()
sqlalchemy supports MySQL and all versions of Python 3. It's nice because you don't have to write SQL; it makes tables look like classes and records look like objects.
BlaXpirit's answer above to use pymysql works great! But one small caveat. The link to pymysql in his comment will take you to https://github.com/petehunt/PyMySQL/ which is for python 2.x. If you are using python 3, you want to download and install pymysql3 (version 3.0.5 as of 5/12/12) from http://pypi.python.org/pypi/PyMySQL3/

Categories

Resources