0

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.

0

1 Answer 1

2
  • 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
Sign up to request clarification or add additional context in comments.

1 Comment

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, filename, filestamp, table, where)) cur.close() Thanks, this saved me from scrubbing the result with the csv module.

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.