3

I am trying to connect to oracle table and execute a sql. I need to export result set to a csv file. My code is below:

import pyodbc
import csv

cnxn = pyodbc.connect("DSN=11g;UID=test101;PWD=passwd")
cursor = cnxn.cursor()
cursor.execute(sql)
row = cursor.fetchall()
with open('data.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    for line in row:
        a.writerows(line)

cursor.close()

when I do print to line within for loop, I get something like this:

('Production', 'farm1', 'dc1prb01', 'web')
('Production', 'farv2', 'dc2pr2db01', 'app.3')
('Production', 'farm5', 'dc2pr2db02', 'db.3')

this is not working. Any ideas what I might be missing?

3
  • 2
    Can you explain - this is not working ? How is it not working? What else are you getting? Commented Aug 19, 2015 at 20:25
  • He just used the wrong method for csv.writer, Padraic answer is the correct one. Commented Aug 19, 2015 at 20:29
  • I get this error: with open('data.csv', 'w', newline='') as fp: TypeError: 'newline' is an invalid keyword argument for this function Commented Aug 19, 2015 at 20:31

1 Answer 1

6

It would be writerow for a single row:

 a.writerow(line)

writerows expects an iterable of iterables, so it will iterate over the substrings writing each char individually.

If you want to use writerows call it on row:

    row = cursor.fetchall()
    with open('data.csv', 'w', newline='') as fp:
            a = csv.writer(fp, delimiter=',')
            a.writerows(row)

If you are using python2 remove newline='', newline is a *python*3 keyword:

  row = cursor.fetchall()
    with open('data.csv', 'w') as fp:
            a = csv.writer(fp, delimiter=',')
            a.writerows(row)
Sign up to request clarification or add additional context in comments.

4 Comments

still not able to execute the sql
If you see ('Production', 'farm1', 'dc1prb01', 'web') how is the sql not working? Using writerows on that will give you P,r,o,d,u,c,t,i,o,n. ....
If I dont use the csv, and just print the line, I can print.
@user1471980, newline="" is for python3 not python2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.