Manipulate . txt file in Ruby and pupular BD?

Asked

Viewed 84 times

2

I need to open a file. txt whatever has a string sequence separated by ";" and needs to be placed each ";" on a vector to then create a loop and insert it into the database.

What do 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 file . txt will have several lines.

1 answer

2


You were well on the right track, missed only the cat jump

I will use an input file for demo

txt groups.

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

Here’s the connection you’ve 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 jump:

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

Upshot:

inserir a descrição da imagem aqui

OPTIMIZING

In case your file is not small, it is very worth using transaction , that same example with 1000 lines took 26.221072s to rotate, using transaction led only 0.343375s

Example with transaction:

   ActiveRecord::Base.connection.transaction do
    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
  end
  • Caaaaaaaaaaara, Perfect!!!! Thank you very much, it helped a lot even

  • Opa que bom que ajudou @Juliano, se a resposta resolver seu problema marque como resposta. Grande abraço. Precisa estamos ai!

  • Boaa @Juliano :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.