Handle .txt file in Ruby and BD pupular?

2

I need to open a .txt file that has a sequence of strings separated by ";" and I need to put every ";" in a vector to later create a loop and insert into the bank.

What I have:

require 'pg'
require 'active_record'


 = File.open('teste.txt')
f_lines = f.read.split(";")

Connection to the bank

conn = ActiveRecord::Base.establish_connection(:adapter => 'postgresql',
                                                :username => 'root', 
                                                :password => "123",
                                                :host => "127.0.0.1",
                                                :database => "db")

#query = "insert into students (name, registration, room, password) values "+ vetor[]
#simulated = ActiveRecord::Base.connection.execute(query)

PS: My .txt file will have multiple lines.

    
asked by anonymous 23.08.2016 / 18:17

1 answer

2

You were well on the right track, you just missed the srsrs cat jump

I'll use an input file for demonstration

groups.txt

'Administradores'; 'adm'; true
'Redatores'; 'red'; false
'Editores'; 'edt'; false
'Leitores'; 'lei'; false

Here is the connection you have already made:

require 'pg'
require 'active_record'

file = File.open('grupos.txt')

ActiveRecord::Base.establish_connection(:adapter => 'postgresql',
                                                :username => 'root', 
                                                :password => "123",
                                                :host => "127.0.0.1",
                                                :database => "db")

And the cat's leap:

file.each_line do |line|
  values = line.split(';').join(',')
  insert_sql = "insert into grupos (nome, slug, padrao) values ( #{values} )"
  ActiveRecord::Base.connection.execute insert_sql
end

Result:

OPTIMIZING

Ifyourfileisnotsmall,it'sworthusingtransaction,thissameexamplewith1000linestook26.221072storun,usingtransactiontookonly0.343375s

Examplewithtransaction:

ActiveRecord::Base.connection.transactiondofile.each_linedo|line|values=line.split(';').join(',')insert_sql="insert into grupos (nome, slug, padrao) values ( #{values} )"
      ActiveRecord::Base.connection.execute insert_sql
    end
  end
    
24.08.2016 / 13:27