Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When creating a CSV file, do you need to escape certain characters?

Tags:

mysql

ruby

csv

I am generating a CSV file from Ruby. The problem is a column string will contain double quotes, single quotes. How can I escape these things?

"Mary had a little so called \"lamb\"","34","none"
"something is not \"right\"","23","none"

Each column is enclosed in double quotes followed by comma (and no space), and written into a file.

Additionally, how do you insert CSV into MySQL? Would you need to use something like PHP's mysql_real_escape_string?

like image 338
puqt Avatar asked Feb 28 '23 01:02

puqt


2 Answers

Writing CSV data is easy, the simplest way is to replace every instance of a double quote with 2 double quotes and then surround the whole thing in double quotes. Alternatively, if your data does not contain double quotes, commas, carriage returns, linefeeds, or leading/trailing space, you don't have to surround the data with quotes or worry about escaping. You can find more information here.

Parsing CSV is much more complex, especially if you try to handle various forms of malformed data out there, in this case you almost certainly want to use an existing module.

like image 96
Robert Gamble Avatar answered Mar 05 '23 16:03

Robert Gamble


Use FasterCSV. Do not roll your own CSV generation.

http://fastercsv.rubyforge.org/

like image 22
Mike H Avatar answered Mar 05 '23 16:03

Mike H