Today your leader to find you, hope you can help him a little busy, he is now anxious to go to the meeting. What can I do for you? You're curious.
He said to you, the current database of your project has a user information table, which contains a very user data, now need to complete a selective query user information function. He said he'd pass it on to you. An array that contains a lot of user names, and you need to check out their corresponding data according to the username.
This function is very simple, you readily agreed. Since your project is using a MySQL database, you quickly write the following code:
Require ' MySQL '
class queryutil
def find_user_info usernames
@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 (S QL);
Result.each_hash do |row|
#Process the data read from the database
End
#The data should be assembled into an object and returned later, omit the
ensure
@db.
Here, the SQL statements are assembled according to the incoming user array group, and then the corresponding rows are found in the database. For the sake of debugging, you will also print out the assembled SQL statements.
Then, you write the following code to test this method:
Qutil = queryutil.new
qutil.find_user_info ["Tom", "Jim", "Anna"]
Now run the test code and you find that the program has gone wrong. So you immediately checked the printed SQL statement, and found the problem.
SELECT * from user_info where username = ' Tom ' or username = ' Jim ' or username = ' Anna ' or
The assembled SQL statements add an OR keyword at the end! Because the For loop does not have to add or to the last piece of data, the code is stupid enough to add an or keyword to the last piece of data, causing the SQL statement syntax to go wrong.
What can we do about it?
There it is! You have a flash of inspiration and come up with a solution. After the SQL statements have been assembled, it is better to intercept the last or previous position. So you change the code to look like the following:
Require ' MySQL '
class queryutil
def find_user_info usernames
@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|
#Process the data read from the database
End
#The data should be assembled into an object and returned later, omit the
ensure @db.
Using the Intercept substring method of string, only to the part before the last or, running the test code again, everything is fine, and the printed SQL statement looks like this:
SELECT * from user_info where username = ' Tom ' or username = ' Jim ' or username = ' Anna '
All right, finish it! You are full of confidence.