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'),
)