Oct-08-2021, 09:09 PM
I have a query that may have dynamic number of columns. I have include 2 columns for testing purpose. whenever they added fields to the table the number of columns in query may change. with present code, I am getting output like below
(,1,0,6,5,,, ,',S,t,r,e,e,t, ,L,e,v,e,l, ,4,',)
-----
(,1,1,4,5,,, ,',V,i,c,t,o,r,i,a, ,S,t,r,e,e,t,',)
------
(,1,2,2,2,,, ,',F,r,a,n,k,l,i,n, ,S,t,r,.,',)
-----
*Expected output:
1065
Street Level 4
-----
1145
Victoria Street
-------
1222
Franklin Str.
----
(,1,0,6,5,,, ,',S,t,r,e,e,t, ,L,e,v,e,l, ,4,',)
-----
(,1,1,4,5,,, ,',V,i,c,t,o,r,i,a, ,S,t,r,e,e,t,',)
------
(,1,2,2,2,,, ,',F,r,a,n,k,l,i,n, ,S,t,r,.,',)
-----
*Expected output:
1065
Street Level 4
-----
1145
Victoria Street
-------
1222
Franklin Str.
----
Quote:Python Code:
----------------
import cx_Oracle
from configparser import ConfigParser
filename='config_db.ini'
parser = ConfigParser()
parser.read(filename)
my_user=parser['oracle']['username']
my_dsn=parser['oracle']['dsn']
my_passwd=parser['oracle']['password']
print('user:',my_user)
sql_1= """
select cust_id,address addr from
(
select 1065 cust_id,'Street Level 4' address from dual union all
select 1145 cust_id,'Victoria Street' address from dual union all
select 1222 cust_id,'Franklin Str.' address from dual
)
"""
##No of column in the query would be dynamic...today 2 fields .... they may add more fields to the db table
conn = cx_Oracle.connect(my_user,my_passwd,my_dsn)
cursor = conn.cursor()
cursor.execute(sql_1)
qry_result = cursor.fetchall()
cursor.close()
conn.close()
with open('test_file.txt','w') as wf:
for i in qry_result:
print(type(i))
print('i:',i) ## string here
#f_result= ','.join(map(','.join,i))
f_result= ','.join(str(i))##converting into tuple
print(type(f_result))
print('f_result:',f_result)
wf.write(f_result+"\n")##writing to the file
wf.write('----------'+"\n")