繁体   English   中英

通过纯Ruby,数据库连接将哈希插入MySQL

[英]Insert hash to MySQL via pure Ruby, database connection

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

我将提供一种用于插入数据的方法:

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)位。

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM