简体   繁体   中英

Construct a valid MySQL query using Ruby/MySQL

If using the Ruby/MSQL library I returned an object of type Mysql::Result, how would I construct a string that loops through the object and constructs a valid MySQL query? I am having trouble figuring out how to drop the final comma from the output below, and how to pass this output back to the query() method.

require 'mysql'
dbh = Mysql.real_connect("host", "user", "pass", "db")
res = dbh.query("SELECT name, category FROM animals")
printf "INSERT INTO animals (name, category) VALUES (\n"
res.each_hash do |row|
printf "('%s', '%s'),\n", row["name"], row["category"]
end
printf ")\n"

#Output    
INSERT INTO animals (name, category) VALUES (
    ('snake', 'reptile'),
    ('frog', 'amphibian'),
    ('tuna', 'fish'),
    ('raccoon', 'mammal'),
    )
values = []
res.each_row do |r|
  values << "(#{r.map{|x| dbh.quote(x) }.join(", ")})"
end
query =<-SQL
  INSERT INTO animals(name, category) VALUES
    (#{values.join(",\n")}
    )
SQL

puts query

I'd use join in this case, so rather than looping, and adding a comma each time, do something like:

["One", "Two", "Three"].join(',')

You'll need to turn your hash into an array containing the elements you are interested in first, of course! Try this:

(res.each_hash{|row| "(#{row["name"]}, #{row["category"]})"}).join(",")

One way to do this would be to:

    require 'mysql'    
    dbh = Mysql.real_connect("host", "user", "pass", "db")    
    res = dbh.query("SELECT name, category FROM animals")   
    stmt = "INSERT INTO animals (name, category) VALUES ("    
    res.each_hash do |row|
        stmt << "(#{row["name"]}, #{row["category"]})"  
    end    
    stmt << ")"

"how to pass this output back to the query() method"

     dbh.query(stmt)

通常,如果您不想只使用任何Ruby魔术(如.join()),则可以按索引循环遍历数组/哈希,并且如果不是最后一个元素,则仅添加逗号:

  if(index < array.length) string << ",\n"

Thanks for all the suggestions. Using Ben Hughes' example, here is the 'hashed' version:

values = []
res.each_hash do
  |row| values << "('#{row.map{|d,x| dbh.quote(x) }.join("', '")}')" 
  end
puts values.join(",")

query="INSERT INTO animals (name, category) VALUES #{values.join(", ")}"
dbh.query(query)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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