slooow
slooow

Reputation: 359

output mysql table into comma separated file with python: syntax error

I am trying to write a MySQL table into a csv table with proper comma separation. It works without formatting and the result is a tab separated file. I need however a comma separated file and I am getting a syntax error. Here is the code:

def export_csv(cxn, filename,filestamp,table, cols='*', where='1'):  
     cur = cxn.cursor()  
     cur.execute("select %s \ 
     into outfile '/tmp/%s-%s.csv' \  
     fields terminated by ',' optionally enclosed by '\"' \  
     escaped by '\\' \  
     lines terminated by '\n'  
     from %s \  
     where %s " \  
     % (cols, table, where, filename, filestamp))  
     cur.close()

It works in pure MySQL. I tried to add more escapes, to no avail.

Upvotes: 0

Views: 569

Answers (1)

Janne Karila
Janne Karila

Reputation: 25197

  • Use triple quotes ''' around a string that spans multiple lines, in this case around the select statement.

EDIT (there's more...)

  • Don't add a backslash at end of line inside the triple-quoted string
  • To pass a backslash to MySQL, escape with backslash \\, or add an r before opening quotes to mark raw string

Upvotes: 2

Related Questions