【问题标题】:Reading a CSV file into Ruby using Sequel and the SQLite3 gems使用 Sequel 和 SQLite3 gems 将 CSV 文件读入 Ruby
【发布时间】:2014-09-05 23:22:14
【问题描述】:

我需要从两个 CSV 文件中读取数据并将它们加载到 SQLite3 的两个不同表中。然后我想查询这两个表并创建一个需要输出到新 CSV/Excel 中的新数据集。这样做的最佳方法是什么?

我正在考虑 SQLite3、Sequel 和 FasterCSV 的组合。

还有一个 CSV2SQLite gem,但我不知道如何使用它。

另外,如果有人有代码 sn-ps,那将不胜感激。

【问题讨论】:

标签: ruby csv sqlite sequel fastercsv


【解决方案1】:
require 'csv'

csv_file_1 = CSV.read("/home/user/Desktop/first_file_1.csv")
csv_file_2 = CSV.read("/home/user/Desktop/first_file_2.csv")

csv_file_1[0][0] = ["name", "phone"] #ect 

#
# logic goes here to work with your csv files 
# 

require 'sequel'
DB = Sequel.sqlite("/home/user/Desktop/csv.db")

DB.create_table :people do 
  primary_key :id
  String :name
  String :phone
end

database = DB[:people]


database.insert(:name => "duck", :phone => "867-5309")

#logic goes here to insert/sort/manipulate your CSV files.  

BOOM 读取 csv 文件并使用 sequel ruby​​ gem 创建表。

【讨论】:

    【解决方案2】:

    我使用另一个代码片段:

    def import_csv(tabname, data)    
      csv = CSV.parse(data, :headers=> true, :header_converters => :symbol )
      DB.create_table(tabname){
        primary_key :id
        csv.headers.each{|col|    
          String col
        }
      } 
      p csv.headers
      DB[tabname].multi_insert(csv.map {|row| row.to_h})
      #~ csv.each{|row|
        #~ DB[tabname].insert(row.to_h)
      #~ }
    end
    

    它读取 CSV 数据并创建一个表格列 CSV 标题(作为字符串)。然后将所有数据复制到表中。

    一个完整的例子:

    #encoding: utf-8
    =begin
    =end
        require 'sequel'
        require 'csv'
        Sequel.extension :pretty_table  #Sequel::PrettyTable.print()/Sequel::PrettyTable.string()
    =begin
    Test data
    =end
        DB = Sequel.sqlite
    
    def import_csv(tabname, data)    
      csv = CSV.parse(data, :headers=> true, :header_converters => :symbol )
      DB.create_table(tabname){
        primary_key :id
        csv.headers.each{|col|    
          String col
        }
      } 
      p csv.headers
      DB[tabname].multi_insert(csv.map {|row| row.to_h})
      #~ csv.each{|row|
        #~ DB[tabname].insert(row.to_h)
      #~ }
    end
    
    import_csv(:tab1, DATA.read)    
    
    DB.tables.each{|table|
      puts table
      Sequel::PrettyTable.print(DB[table])
    }
    
        #~ Sequel::PrettyTable.print(DB[:mytables].filter(Sequel.like(:a, 'a%')))
    __END__
    a,b,c,d,e
    1,2,3,4,5
    1,2,3,4,5
    1,2,3,4,5
    

    【讨论】:

      猜你喜欢
      • 2012-03-19
      • 1970-01-01
      • 2013-08-10
      • 2012-08-05
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2015-02-06
      相关资源
      最近更新 更多