嘿,我是一个绝对的红宝石,希望你能帮助我。 我想用不同的部门(部门A,B,C ......)进行很多SQL查询。
我想将部门保存到数组并迭代它,使用循环等等。
这是我的旧代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.connection.drive_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">SYSTEM</property>
<property name="hibernate.connection.password">****</property>
<property name="show_sql">true</property>
<mapping class="Entity.Address"/>
<mapping class="Entity.Student"/>
</session-factory>
这是我的伪代码:
#!/usr/bin/ruby
require 'mysql2'
##Connect to my Database
db = Mysql2::Client.new(:host => "localhost", :username => "MyUserName", :password => "MyPassword", :port => 3306, :database => "MyTest-Database" )
#Mysql querys
sql_A= "SELECT RMKPI FROM `Table1` WHERE `Department` = 'A' "
sql_B= "SELECT RMKPI FROM `Table1` WHERE `Department` = 'B' "
#Execute the querys
results_PO = db.query(sql_A)
results_DevMuM = db.query(sql_A)
我该怎么做? 非常感谢
答案 0 :(得分:2)
DEPARTMENTS = %w|A B C|
results = DEPARTMENTS.map do |department|
query = "SELECT RMKPI FROM `Table1` WHERE `Department` = '#{department}'"
[department, db.query(query)]
end.to_h
现在你有一个{ departments ⇒ results }
的哈希值。要访问给定部门的结果,请使用:
results['A']
Sidenote :我建议你google ActiveRecord
或任何其他ROM来简化并使数据库查询工作更安全。