title: Insert hash to MySQL via pure Ruby, database connection
body: <p>I'm using mysql gem and Ruby 1.9.3, not using Rails. I have the following:</p>
  
  <pre><code>#!/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"=&gt;"Tuba", "latitude"=&gt;13.7383, "longitude"=&gt;100.5883}
      # Write to DB
  
    ### Loop Ends ###
  
  rescue Mysql::Error =&gt; e
    puts e.errno
    puts e.error
  
  ensure
    con.close if con
  end
  </code></pre>
  
  <p><strong>Questions</strong></p>
  
  <ol>
  <li><code>@place</code> is a hash. How can I quickly insert to the <code>data</code> table other than iterating it?</li>
  <li>The loop will continue until the entire process ends. Should I close the connection after each insert, or leave it open until process ends?</li>
  <li>What if the process terminates unexpectedly? Will it affect the data if connection is not closed properly?</li>
  </ol>
  
  <p><strong>UPDATE: My first try:</strong></p>
  
  <pre><code>col = @place.map { | key, value | key } # =&gt; ["name", "latitude", "longitude"]
  result = @place.map { | key, value | value } # =&gt; ["Tuba", 13.7383, 100.5883]
  con.query("INSERT INTO shops (#{col}) VALUES(#{result});")
  </code></pre>
  
  <p>This, as expected, generates the following error:</p>
  
  <pre><code>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
  </code></pre>