cx_Oracle callfunc()

I like wrapping database queries in stored procedures: it keeps the SQL in the database, where Oracle can track its dependencies and flag if some change makes it invalid.  Here’s an example using Oracle’s demo schema SCOTT:

CREATE OR REPLACE PACKAGE emp_extract_k
AS
   TYPE emp_t
   IS
      RECORD( ename  varchar2( 10 ), hiredate date, sal     number( 7, 2 ) );
   TYPE emp_csr_t IS REF CURSOR
      RETURN emp_t;
   FUNCTION get_emps
      RETURN emp_csr_t;
END;
/
CREATE OR REPLACE PACKAGE BODY emp_extract_k
AS
   FUNCTION get_emps
      RETURN emp_csr_t
   IS
      c   emp_csr_t;
   BEGIN
      OPEN c FOR SELECT   ename, hiredate, sal FROM scott.emp;
      RETURN c;
   END;
END;/

Now suppose I want to take the output from a stored procedure like the one above and write it to a CSV file.  In Python this is trivially easy:

 import cx_Oracle
 import csv
 reportName = 'emp_extract_k.get_emps'
 connection = cx_Oracle.connect(userid)
 cursor = connection.cursor()
 rs = cursor.callfunc(reportName, cx_Oracle.CURSOR)
 fd = open(reportName+'.csv', 'w')
 csvFile = csv.writer(fd)
 header = []
 [header.append(col_defn[0]) for col_defn in rs.description]
 csvFile.writerow(header)
 for r in rs:
  csvFile.writerow(r)
 fd.close()

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top