Oracle et Python

Le C on sait tous que c’est bien, j’ai découvert Python récemment et je peux vous dire que c’est bien aussi :). Voila comment on peut mettre en place son environnement pour accéder a Oracle a partir de Python.

– On va installer pip : il s’agit d’un package manager pour Python (un peut comme apt pour Ubuntu)

– On installera aussi easy_install (un package manager pour Python aussi)

sudo apt-get install python-setuptools python-dev easy_install pip

– On va ensuite installer VirtualEnv : il s’agit d’un environnement Python complètement isolé de celui de votre machine, donc pas besoin de droits root pour installer des modules Python, les supprimer ou les modifier.

sudo pip install virtualenv virtualenvwrapper

Une fois que c’est fait, ajouter ces lignes dans votre ~/.bashrc :

export WORKON_HOME=$HOME/Python_Projects
export VIRTUALENVWRAPPER_HOOK_DIR=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_LOG_DIR=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--no-site-packages --distribute'
source /usr/local/bin/virtualenvwrapper.sh

Pour que ceci prend effet :

source $HOME/.bashrc

On peut donc créer un environnement virtuel MyFirstVirtualEnv dans lequel on va bosser :

mkvirtualenv MyFirstVirtualEnv

Cette commande créera un répertoire ~/Python_Projects/MyFirstVirtualEnv qui contient un environnement Python prêt a l’emploi. Pour commencer a travailler dans votre nouvel environnement, tapez :

workon MyFirstVirtualEnv

Vous aurez droit a quelque chose comme ça (changement de prompt):

VirtualEnv

Pour quitter votre virtualenv tapez :

deactivate

Pour acceder a Oracle a partir de Python, je vous propose deux méthodes :

– Via ODBC grâce au module PyODBC :  vous devez avoir un environnement ODBC déjà fonctionnel (/etc/odbc.ini, /etc/odbcinst.ini) pour que ça marche. Voila le contenu de ces deux fichiers sur ma machine :

(MyFirstVirtualEnv)toc@tocNewServer:~/Python_Projects/MyFirstVirtualEnv$ cat /etc/odbc.ini
[Oracle]
Application Attributes 	= T
Attributes 		= W
BatchAutocommitMode 	= IfAllSuccessful
CloseCursor 		= F
DisableDPM 		= F
DisableMTS 		= T
Driver 			= Oracle
EXECSchemaOpt 		=
EXECSyntax 		= T
Failover 		= T
FailoverDelay 		= 10
FailoverRetryCount 	= 10
FetchBufferSize 	= 64000
ForceWCHAR 		= F
Lobs 			= T
Longs 			= T
MetadataIdDefault 	= F
QueryTimeout 		= T
ResultSets 		= T
ServerName 		= //192.168.1.95:1521/TOCORACL
SQLGetData extensions 	= F
Translation DLL 	=
Translation Option 	= 0
UserID 			=
(MyFirstVirtualEnv)toc@tocNewServer:~/Python_Projects/MyFirstVirtualEnv$
(MyFirstVirtualEnv)toc@tocNewServer:~/Python_Projects/MyFirstVirtualEnv$ cat /etc/odbcinst.ini
[ODBC]
Trace		= yes
TraceFile	= /tmp/odbc.log

[Oracle]
Description	= Oracle ODBC Connection
Driver		= /usr/lib/oracle/11.2/client/lib/libsqora.so.11.1
Setup		=
FileUsage	=
CPTimeout	=
CPReuse		=

Pour installer le module PyODBC :

workon MyFirstVirtualEnv
pip install pyodbc

Pour tester notre install on va créer un petit script odbc_oracle_demo.py :

#! /usr/bin/env python
 
import pyodbc
 
conn = pyodbc.connect('DSN=Oracle;UID=hr;PWD=human')
curs = conn.cursor()
curs.execute('SELECT * FROM product_component_version')
row = curs.fetchone()
print row

Qu’on execute comme suit :

chmod +x odbc_oracle_demo.py
(MyFirstVirtualEnv)toc@tocNewServer:~/Python_Projects/My_Python_Src/ORACLE$ ./odbc_oracle_demo.py
('NLSRTL ', '11.2.0.1.0', 'Production')

– Via le module cx_Oracle, qu’on peut installer comme suit :

pip install cx_Oracle

Puis on test avec ce script oracle_cx_demo.py :

#! /usr/bin/env python
 
import cx_Oracle
import time
 
# Les informations necessaires pour se connecter a la base
db_user = 'hr'
db_password = 'human'
db_server = '192.168.1.95'
db_port = '1521'
db_name = 'TOCORACL'
 
# On veut juste savoir ca prend combien de temps
start_time = time.clock()
# On se connecte
connection = cx_Oracle.connect("%s/%s@%s:%s/%s" %
    (db_user, db_password, db_server, db_port, db_name))
 
# On cree un curseur pour notre requete
curs = connection.cursor()
 
# on execuste notre requete
curs.execute("""SELECT department_id, first_name, last_name, salary
    FROM HR.employees
    WHERE department_id is not null
    """)
 
print "+------------------+------------------+------------------+------------------+"
print "|",
# On recupere les noms des colonnes
columns_names = curs.description
for column in columns_names:
    print "%16s |" %column[0],
print "\n+------------------+------------------+------------------+------------------+"
 
# On affiche le resultat
for row in curs:
    for column in row:
        print "%16s | " %column,
    print ""
 
# Affichage du temps mis  par le triatement
elapsed_time = time.clock() - start_time
print "Elapsed time = %f s" % elapsed_time
 
# On ferme la connexion
connection.close()

Qu’on teste comme suit :

chmod +x oracle_cx_demo.py
(MyFirstVirtualEnv)toc@tocNewServer:~/Python_Projects/My_Python_Src/ORACLE$ ./oracle_cx_demo.py
+------------------+------------------+------------------+------------------+
|    DEPARTMENT_ID |       FIRST_NAME |        LAST_NAME |           SALARY |
+------------------+------------------+------------------+------------------+
              50 |            Donald |          OConnell |            2600.0 |
              50 |           Douglas |             Grant |            2600.0 |
              10 |          Jennifer |            Whalen |            4400.0 |
              20 |           Michael |         Hartstein |           13000.0 |
              20 |               Pat |               Fay |            6000.0 |
              40 |             Susan |            Mavris |            6500.0 |
              70 |           Hermann |              Baer |           10000.0 |
             110 |           Shelley |           Higgins |           12008.0 |
             110 |           William |             Gietz |            8300.0 |
              90 |            Steven |              King |           24000.0 |
              90 |             Neena |           Kochhar |           17000.0 |
              90 |               Lex |           De Haan |           17000.0 |
              60 |         Alexander |            Hunold |            9000.0 |
              60 |             Bruce |             Ernst |            6000.0 |
              60 |             David |            Austin |            4800.0 |
              60 |             Valli |         Pataballa |            4800.0 |
              60 |             Diana |           Lorentz |            4200.0 |
             100 |             Nancy |         Greenberg |           12008.0 |
             100 |            Daniel |            Faviet |            9000.0 |
             100 |              John |              Chen |            8200.0 |
             100 |            Ismael |           Sciarra |            7700.0 |
             100 |       Jose Manuel |             Urman |            7800.0 |
             100 |              Luis |              Popp |            6900.0 |
              30 |               Den |          Raphaely |           11000.0 |
              30 |         Alexander |              Khoo |            3100.0 |
              30 |            Shelli |             Baida |            2900.0 |
              30 |             Sigal |            Tobias |            2800.0 |
              30 |               Guy |            Himuro |            2600.0 |
              30 |             Karen |        Colmenares |            2500.0 |
              50 |           Matthew |             Weiss |            8000.0 |
              50 |              Adam |             Fripp |            8200.0 |
              50 |             Payam |          Kaufling |            7900.0 |
              50 |            Shanta |           Vollman |            6500.0 |
              50 |             Kevin |           Mourgos |            5800.0 |
              50 |             Julia |             Nayer |            3200.0 |
              50 |             Irene |       Mikkilineni |            2700.0 |
              50 |             James |            Landry |            2400.0 |
              50 |            Steven |            Markle |            2200.0 |
              50 |             Laura |            Bissot |            3300.0 |
              50 |             Mozhe |          Atkinson |            2800.0 |
              50 |             James |            Marlow |            2500.0 |
              50 |                TJ |             Olson |            2100.0 |
              50 |             Jason |            Mallin |            3300.0 |
              50 |           Michael |            Rogers |            2900.0 |
              50 |                Ki |               Gee |            2400.0 |
              50 |             Hazel |        Philtanker |            2200.0 |
              50 |            Renske |            Ladwig |            3600.0 |
              50 |           Stephen |            Stiles |            3200.0 |
              50 |              John |               Seo |            2700.0 |
              50 |            Joshua |             Patel |            2500.0 |
              50 |            Trenna |              Rajs |            3500.0 |
              50 |            Curtis |            Davies |            3100.0 |
              50 |           Randall |             Matos |            2600.0 |
              50 |             Peter |            Vargas |            2500.0 |
              80 |              John |           Russell |           14000.0 |
              80 |             Karen |          Partners |           13500.0 |
              80 |           Alberto |         Errazuriz |           12000.0 |
              80 |            Gerald |         Cambrault |           11000.0 |
              80 |             Eleni |           Zlotkey |           10500.0 |
              80 |             Peter |            Tucker |           10000.0 |
              80 |             David |         Bernstein |            9500.0 |
              80 |             Peter |              Hall |            9000.0 |
              80 |       Christopher |             Olsen |            8000.0 |
              80 |           Nanette |         Cambrault |            7500.0 |
              80 |            Oliver |           Tuvault |            7000.0 |
              80 |           Janette |              King |           10000.0 |
              80 |           Patrick |             Sully |            9500.0 |
              80 |             Allan |            McEwen |            9000.0 |
              80 |           Lindsey |             Smith |            8000.0 |
              80 |            Louise |             Doran |            7500.0 |
              80 |            Sarath |            Sewall |            7000.0 |
              80 |             Clara |           Vishney |           10500.0 |
              80 |          Danielle |            Greene |            9500.0 |
              80 |            Mattea |           Marvins |            7200.0 |
              80 |             David |               Lee |            6800.0 |
              80 |            Sundar |              Ande |            6400.0 |
              80 |              Amit |             Banda |            6200.0 |
              80 |              Lisa |              Ozer |           11500.0 |
              80 |          Harrison |             Bloom |           10000.0 |
              80 |            Tayler |               Fox |            9600.0 |
              80 |           William |             Smith |            7400.0 |
              80 |         Elizabeth |             Bates |            7300.0 |
              80 |           Sundita |             Kumar |            6100.0 |
              80 |             Ellen |              Abel |           11000.0 |
              80 |            Alyssa |            Hutton |            8800.0 |
              80 |          Jonathon |            Taylor |            8600.0 |
              80 |              Jack |        Livingston |            8400.0 |
              80 |           Charles |           Johnson |            6200.0 |
              50 |           Winston |            Taylor |            3200.0 |
              50 |              Jean |            Fleaur |            3100.0 |
              50 |            Martha |          Sullivan |            2500.0 |
              50 |            Girard |             Geoni |            2800.0 |
              50 |           Nandita |          Sarchand |            4200.0 |
              50 |            Alexis |              Bull |            4100.0 |
              50 |             Julia |         Dellinger |            3400.0 |
              50 |           Anthony |            Cabrio |            3000.0 |
              50 |             Kelly |             Chung |            3800.0 |
              50 |          Jennifer |             Dilly |            3600.0 |
              50 |           Timothy |             Gates |            2900.0 |
              50 |           Randall |           Perkins |            2500.0 |
              50 |             Sarah |              Bell |            4000.0 |
              50 |           Britney |           Everett |            3900.0 |
              50 |            Samuel |            McCain |            3200.0 |
              50 |             Vance |             Jones |            2800.0 |
              50 |             Alana |             Walsh |            3100.0 |
              50 |             Kevin |            Feeney |            3000.0 |
Elapsed time = 0.010000 s
(MyFirstVirtualEnv)toc@tocNewServer:~/Python_Projects/My_Python_Src/ORACLE$

Si vous voyez l’erreur suivante :

ImportError: libclntsh.so .....

Vérifiez que vous avez bien installer les libs client Oracle et que dans votre LD_LIBRARY_PATH vous avez bien : /usr/lib/oracle/11.2/client/lib.

Pour plus d’infos sur ces deux APIs :
http://code.google.com/p/pyodbc/w/list
http://cx-oracle.sourceforge.net/html/index.html

Publicité

Votre commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l’aide de votre compte WordPress.com. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s