我正在使用 mysql gem 和 Ruby 1.9.3,而不是使用 Rails。我有以下内容:
#!/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
问题
@place
是一个哈希。data
除了迭代之外,如何快速插入表?- 循环将继续,直到整个过程结束。我应该在每次插入后关闭连接,还是保持打开状态直到过程结束?
- 如果进程意外终止怎么办?如果连接没有正确关闭会影响数据吗?
更新:我的第一次尝试:
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});")
正如预期的那样,这会产生以下错误:
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