2017-08-25 21 views
0

我CSV文件導入到表導入CSV於Postgres在使用COPY時添加其他列稱爲import_csv如何從軌

表已列first_name, last_name, email, phone_number, organization_id

我導入CSV使用以下代碼

file = params[:file] 
    filePath = file.path 
    fileName = File.basename filePath 

    pg = ActiveRecord::Base.connection 
    rc = pg.raw_connection 
    rc.exec("COPY import_csv (first_name, last_name, email, phone_number) FROM STDIN WITH CSV") 

    file = File.open(filePath) 
    file::gets 

    while !file.eof? 
    # Add row to copy data 
    rc.put_copy_data(file.readline) 
    end 

我想知道如何設置organization_id字段,而不必將其導入到.CSV文件中。

回答

0
  1. 將您的csv文件導入到新表中。

  2. 現在,隨着ADD COLUMN命令modificate表模式:

    RC = pg.raw_connection

    ...

    rc.exec( 「ALTER TABLE import_csv ADD COLUMN的organization_ID整數;」)

現在應該做。

+0

我正在插入具有列一個已經存在的表中導入的時間 – RickS

+0

@RickS我看到,作爲變通解決方案,您可以創建臨時表,將csv導入到其中,並使用psql'insert'命令從臨時錶轉換爲實際表,如此處所述https://stackoverflow.com/questions/12618232/copy-一些csv-files-into-a-tables的列 – Med

+0

我試過了,但是使用這種方法的時間長了20倍,我希望有一些方法可以修改COPY命令,所以我可以爲一行添加一個值,但它已經幾個小時了,我還沒有開始und anything – RickS

0

我能夠用COPY命令之前修改CSV周圍找工作如下:

require 'csv' 

    # Load the original CSV file 
    rows = CSV.read(filePath, headers: true).collect do |row| 
    hash = row.to_hash 
    hash.merge('phone_number' => '0') 
    hash.merge('a1' => hash['organization_id'].to_s + '#{organization_id}') 
    end 

    # Extract column names from first row of data 
    column_names = rows.first.keys 
    txt = CSV.generate do |csv| 
    csv << column_names 
    rows.each do |row| 
     # Extract values for row of data 
     csv << row.values 
    end 
    end 

這讓我加入組織ID,而無需將其添加到CSV。

如果任何人有什麼更好的建議,請讓我知道,因爲在導入21000的記錄只是重寫帶來它需要從0.045868到0.858213秒