classQueryUtil deffind_user_infousernames @db = Mysql.real_connect("localhost","root","123456","test",3306); sql = "select * from user_info where " usernames.each do|user| sql << "username = '" sql << user sql << "' or " end puts sql result = @db.query(sql); result.each_hash do|row| #处理从数据库读出来的数据 end #后面应将读到的数据组装成对象返回,这里略去 ensure @db.close end end
select * from user_info where username = 'Tom'or username = 'Jim'or username = 'Anna'or
拼装出来的SQL语句在最后多加了一个 or 关键字!因为for循环执行到最后一条数据时不应该再加上or,可是代码很笨地给最后一条数据也加了or关键字,导致SQL语句语法出错了。 这可怎么办呢? 有了!你灵光一闪,想出了一个解决办法。等SQL语句拼装完成后,截取到最后一个or之前的位置不就好了么。于是你将代码改成如下所示:
classQueryUtil deffind_user_infousernames @db = Mysql.real_connect("localhost","root","123456","test",3306); sql = "select * from user_info where " usernames.each do|user| sql << "username = '" sql << user sql << "' or " end sql = sql[0 .. -" or ".length] puts sql result = @db.query(sql); result.each_hash do|row| #处理从数据库读出来的数据 end #后面应将读到的数据组装成对象返回,这里略去 ensure @db.close end end
classStrategy defget_sqlusernames raise "You should override this method in subclass." end end
然后定义两个子类都继承上述父类,并将两种拼装SQL语句的算法分别加入两个子类中:
1 2 3 4 5 6 7 8 9 10 11
classStrategy1 defget_sqlusernames sql = "select * from user_info where " usernames.each do|user| sql << "username = '" sql << user sql << "' or " end sql = sql[0 .. -" or ".length] end end
1 2 3 4 5 6 7 8 9 10 11 12 13
classStrategy2 defget_sqlusernames sql = "select * from user_info where " need_or = false usernames.each do|user| sql << " or "if need_or sql << "username = '" sql << user sql << "'" need_or = true end end end