Question

I did a ruby script that parses a lot of files in ruby data structures, like hashes for example.

I need to insert all this data in a MySQL database.

What I found:

mysql2

tmtm

dbi

Is there some native way to do this?

Thanks for any help

EDIT

Lets say that I have a hash with 100 entries like this:

hash = {"a" => 1, "b" => 2 ..., "c" => 100}

I would like to create a table at mysql with all this columns. I am afraid of Active Record is gonna be hard to do that.

PS: Im not using Rails, just a simple ruby script

Was it helpful?

Solution

If I were you, I would prefer ActiveRecord, because I don't have to clutter my code with lots of SQL statements. Besides activerecord makes life easier.

Set it up like this

require 'active_record'

ActiveRecord::Base.establish_connection( 
 :adapter => "mysql2",
 :host => "host",
 :username=>"user",
 :password=>"user",
 :database => "your_db"
)

Then use tables like this

class SingularTableName < ActiveRecord::Base
  has_many :table_relationship
end

Then query like this

SingularTableName.all #=> all records
SingularTableName.first #=> first record
SingularTableName.where("query")
SingularTableName.create("...) #=> create a record/row

You can find more methods here => http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Update:

To overcome plural table names and default primary key, you can use

class AnyName < ActiveRecord::Base
  self.table_name = 'your table name'
  self.primary_key = 'your primary key'
  ...
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top