我从 SQL 导出表和查询。
读取 csv 的 ruby (1.9+) 方法似乎是:
require 'csv'
CSV.foreach("exported_mysql_table.csv", {:headers=>true}) do |row|
puts row
end
如果您的数据是这样的,这将非常有用:
"name","email","potato"
"Bob","bob@bob.bob","omnomnom"
"Charlie","char@char.com","andcheese"
"Doug","diggyd@diglet.com","usemeltattack"
工作正常(第一行是标题,属性)。但是,如果数据是这样的:
"id","name","email","potato"
1,"Bob","bob@bob.bob","omnomnom"
2,"Charlie","char@char.com","andcheese"
4,"Doug","diggyd@diglet.com","usemeltattack"
然后我们得到错误:
.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1894:in `block (2 levels) in shift': Missing or stray quote in line 2 (CSV::MalformedCSVError)
我认为这是因为 id 存储为数字,而不是字符串,因此没有引号,并且 csv 解析器希望所有条目都有引号。理想情况下,我想将“Bob”读为字符串,将 1 读为数字(并将其填充到哈希哈希中)
(尝试过“FasterCSV”,自 ruby 1.9 以来,该 gem 变成了“csv”)
编辑:
有人指出该示例运行良好(derp),在错误的地方寻找,多行字段出错,问题移至Ruby CSV 读取多行字段