简体   繁体   中英

How can oracle update query generating a csv file and print or write the result in a particular path location through python

Can anyone please help me regarding my post: I am not able to print the oracle update query result in a csv file in particular path location through python. I am able to generate the csv file for oracle select query result in same particular location path through python but whenever I am trying to create a new csv file for update query result,I able to generate the csv file in that particular location but unable to print the oracle update query result in that generated csv file through python.

Sample code:

import cx_Oracle 
import csv 
import pandas as pd
db = cx_Oracle.connect ('user/pass@host:port/service_name')
SQL = "select e.empno as employee_number,e.ename as employee_name ,e.sal as salary,d.deptno as department_number,d.dname as department_name from emp e,dept d where e.deptno=d.deptno order by e.empno,e.ename,e.sal,d.deptno,d.dname"
print(SQL)
cursor = db.cursor()
f = open("e:\\OT_DIR\\employeedetails1.csv", "w")   ## path directory where ever your csv file want to save
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_NONNUMERIC)
r = cursor.execute(SQL)
## this takes the column names
col_names = [row[0] for row in cursor.description]
writer.writerow(col_names)
for row in cursor:
   writer.writerow(row)
f.close()
  # reading the csv file
df = pd.read_csv("E:\\OT_DIR\\employeedetails1.csv")
df.to_csv("employeedetails1.csv", index=False) 
print(df) 

## updating the column value/data
SQL1 = '''update dept set dname='xyz' where dname = 'SALES'and exists (select distinct 1 from 
emp,dept where emp.deptno= dept.deptno )'''
cursor.execute(SQL1)
db.commit()
print(cursor.rowcount, "record(s) affected")
print(SQL1)
f1 = open("e:\\OT_DIR\\res2.csv", "w")   ## path directory where ever your csv file want to save
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_NONNUMERIC)
r = cursor.execute(SQL1)
f1.close()

what modification needed here for printing the update query result in csv file for that particular path location,kindly give all your valuable suggestions...Thank you all..

The UPDATE will change the data in the database but not return it to Python. To get data into Python you need to run a SELECT statement after you execute UPDATE.

For large numbers of rows, don't forget to tune arraysize , see the cx_Oracle doc https://cx-oracle.readthedocs.io/en/latest/user_guide/tuning.html#tuning-fetch-performance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM