I'm using mysql gem and Ruby 1.9.3, not using Rails. I have the following:
#!/bin/env ruby
# encoding: utf-8
require 'rubygems'
require 'mysql'
# Open DB connection
begin
con = Mysql.new 'localhost', 'root', '', 'data'
con.query("CREATE TABLE IF NOT EXISTS
shops(id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
latitude DECIMAL(15,10),
longitude DECIMAL(15,10)
)")
### Loop Starts ###
...
@place = {"name"=>"Tuba", "latitude"=>13.7383, "longitude"=>100.5883}
# Write to DB
### Loop Ends ###
rescue Mysql::Error => e
puts e.errno
puts e.error
ensure
con.close if con
end
Questions
@placeis a hash. How can I quickly insert to thedatatable other than iterating it?- The loop will continue until the entire process ends. Should I close the connection after each insert, or leave it open until process ends?
- What if the process terminates unexpectedly? Will it affect the data if connection is not closed properly?
UPDATE: My first try:
col = @place.map { | key, value | key } # => ["name", "latitude", "longitude"]
result = @place.map { | key, value | value } # => ["Tuba", 13.7383, 100.5883]
con.query("INSERT INTO shops (#{col}) VALUES(#{result});")
This, as expected, generates the following error:
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use
near '["name", "latitude", "longitude"] at line 1
gem install mysqlright? If anything more need,could you help me?gem install mysql, then add the 2requirelines in your Ruby file; if Rails, you putgem mysql2in your Gemfile.require 'rubygems'.. :) I think so.. Do I need to install MySQL server seperately ?