我有一堆从employee_holiday_years这个SQL
红宝石 - 遍历与SQL语句中找到记录
选择id其中起始日期=“2015年1月1日”和EMPLOYEE_ID在(从员工选择ID找到的记录where join_date>'2014-12-31')and allowance_from_last_year <> 0;
我需要使用Ruby遍历此SQL
返回的记录,并针对每一个运行几个Ruby命令。这可能吗?
我有一堆从employee_holiday_years这个SQL
红宝石 - 遍历与SQL语句中找到记录
选择id其中起始日期=“2015年1月1日”和EMPLOYEE_ID在(从员工选择ID找到的记录where join_date>'2014-12-31')and allowance_from_last_year <> 0;
我需要使用Ruby遍历此SQL
返回的记录,并针对每一个运行几个Ruby命令。这可能吗?
通过红宝石你可以试试这个让你有mysql
适配器和ruby
还安装你有
数据库名称TESTDB
用户名testuser
密码test123
主持人:localhost
require "dbi"
begin
dbh = DBI.connect("DBI:Mysql:TESTDB:localhost",
"testuser", "test123")
sth = dbh.prepare("select id from employee_holiday_years where start_date = '2015-01-01' and employee_id in(select id from employees where join_date > '2014-12-31') and allowance_from_last_year <> 0;")
sth.execute(1000)
#iterate through the return records
sth.fetch do |row|
printf row[0], row[1] #to print the row
end
sth.finish
rescue DBI::DatabaseError => e
puts "An error occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
ensure
# disconnect from server
dbh.disconnect if dbh
end
sql返回数组,所以使用数组迭代。
e.g
recoreds.each do |record|
p record.inspect
end
这是我想出了
client = Mysql2::Client.new(:host => "localhost", :username => "root", :database => "mydatabase")
results = client.query("select * from mytable where...", :symbolise_keys => true)
results.each do |row|
do stuff...
end
我们需要更多的信息。你如何发送该SQL语句?您是使用Active Record ORM还是只使用驱动程序?哪一个?向我们展示您正在使用的代码的最小示例。 –