简体   繁体   中英

How do I import a text file from a website into the database line by line in Ruby

I need to import a file from a link from a website with a text file using Ruby.

I can import the entire text into a single variable (I didn't include my specific link):

text = Net::HTTP.get( URI.parse( "http://www.link.com/text.txt" ) )

but I don't know how to import line by line into the database. I need to be able to read it like an array, like this:

text.each do |line|
  Thing.create :variable => line
end

That code would save each line into the database in the "things" table as "variable". If this were my text file:

abc
def
ghi
jkl

This is what the table should look like in the database:

things

id variable
1  abc
2  def
3  ghi
4  jkl

Once again, I need to know how to import a text file from a website (not a disk drive) to achieve the above result. Thanks.

I would split the data on newlines and then call each.

text = Net::HTTP.get( URI.parse( "http://www.link.com/text.txt" ) )
text.split("\n").each do
    ...
end

I would then use the Mysql2 gem to insert the values into your database.

db = Mysql2::Client.new(connection_params)
db.query(insert_statement)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM