Sunday 5 January 2014

Connect oracle database in python

I have implemented this program which will connect to Oracle database and retrieve data from database, tables and containing data. we can read all column row data from this program.

for retrieving the Oracle data 1st we have to install one library which is cx_Oracle library. Download this library from here Download.

Through this library, it will connect to Oracle server by hostname, username, password and fetch all data like database, tables and tables data.


db = cx_Oracle.connect("username", "password", "host")
c = db.cursor()
c.execute(u"SELECT OWNER,count(*) table_count FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'TABLE' GROUP BY OWNER")
for ro in c.fetchall():
   x=ro[0]
   try:
      c.execute("select owner, object_name from all_objects where object_type in ('TABLE','VIEW') and owner = '"+x+"'")
      for rem in c.fetchall():
          y=rem[1]
          try:
             c.execute("select * from "+y)
             for row in c.fetchall():
                 print row
          except:
             print "error in data"
   except:
      print "Error in table for retrieving data"

 
This username & password are Oracle credentials
If you want to connect remote Oracle then you have to use below code for it. it will connect through ip address. 


db = cx_Oracle.connect("username", "password", "hostname or IP address(like as 192.168.1.4)")
c = db.cursor()
c.execute(u"SELECT OWNER,count(*) table_count FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'TABLE' GROUP BY OWNER")
for ro in c.fetchall():
   x=ro[0]
   try:
      c.execute("select owner, object_name from all_objects where object_type in ('TABLE','VIEW') and owner = '"+x+"'")
      for rem in c.fetchall():
          y=rem[1]
          try:
             c.execute("select * from "+y)
             for row in c.fetchall():
                 print row
          except:
             print "error in data"
   except:
      print "Error in table for retrieving data"

Thanks guys

No comments:

Post a Comment