Python: Run query on a Oracle Database and save the result in a csv file

import cx_Oracle

conn_str = u'myuser/mypassword@192.168.1.87/CGFLUC'
con = cx_Oracle.connect(conn_str)
#print con.version
c = con.cursor()
c.execute(u'SELECT * FROM tblbooks')
with open('ans.csv', 'w') as text_file:
    text_file.write('Book Author \n')
    for row in c:
        text_file.write(row[0] + ' ' + row[1] + '\n')
con.close()

=============================================

EXPLANATION:

1.  text_file.write('Book Author \n') : This line is the fields of the table. If you don't need fields in your csv, remove it.

2. You can write with open('ans.csv', 'w') as text_file: if you want to store result in .txt file.

3. The extension cx_Oracle 5.0.2 also need to be installed.

Comments