1

我正在使用 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

问题

  1. @place是一个哈希。data除了迭代之外,如何快速插入表?
  2. 循环将继续,直到整个过程结束。我应该在每次插入后关闭连接,还是保持打开状态直到过程结束?
  3. 如果进程意外终止怎么办?如果连接没有正确关闭会影响数据吗?

更新:我的第一次尝试:

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
4

2 回答 2

4

我会制作一种插入数据的方法:

def insert_place(hash, con)
   statement = "INSERT INTO shops (name, latitude, longitude) VALUES (#{hash['name']}, #{hash['latitude']}, #{hash['longitude']});"
   con.query(statement)
end

此方法将您的哈希和连接对象作为参数。您应该尽可能重用您的连接。

然后在你的循环中,我会像这样使用这个方法:

@place = {"name"=>"Tuba", "latitude"=>13.7383, "longitude"=>100.5883}
insert_place(@place, con)

最后回答你的最后一个问题......如果程序在你的循环中间终止,我看不到任何会“破坏”你的数据的东西,因为它是一个单一的查询,它要么成功要么失败......之间。如果您希望在发生故障时能够再次运行脚本,则需要确定您停止的位置,因为再次运行会导致重复。

您可以手动执行此操作并适当地管理您的数据

或者

您可以将其添加到您的 insert_place 方法中,这样如果该条目已经在数据库中,它将跳过 con.query(statement) 位。

于 2013-09-20T19:19:38.803 回答
-1

在我看来,您需要从数组中提取值

con.query("INSERT INTO shops (#{*col}) VALUES(#{*result});")

可以对代码进行一些改进。我希望这会奏效

col = @place.keys # => ["name", "latitude", "longitude"]
result = @place.values # => ["Tuba", 13.7383, 100.5883]
con.query("INSERT INTO shops (#{*col}) VALUES(#{*result});")
# (not tested variant)
con.query("INSERT INTO shops (?) VALUES(?);", col, result)
于 2013-09-20T19:58:52.627 回答