suresh suresh - 1 year ago 71
Ruby Question

Why this code does not give expected output?

I am learning the database operations in ruby. I was experimenting the database operations.

For example,


db_con = PG.connect :dbname => 'sureshkumar', :user => 'sureshkumar'
db_con.prepare 'get_result', "SELECT * from users;"
users_name = db_con.exec_prepared 'get_result'
if users_name != nil
puts users_name.values
puts "There is no users available in the table users"

rescue PG::Error => e
puts e.message
db_con.close if db_con

The table users contains only two columns. They are,


If the table does not contains any rows, then the exec_prepared statement does not returns any rows.

In this case, why the if condition does not gets false ?

Then how do I check the exec_prepared method doesn't returns any single rows ?

Answer Source

users_name = db_con.exec_prepared 'get_result' will never return nil to users_name.

According to the documentation of PG::Connection#exec_prepared it will return PG::Result object. So, users_name object can never be nil. It will always be an instance of PG::Result.

So, to check whether you have any rows returned from the query execution you need to check if this PG::Result object has any values in it. In your case, users_name variable contains the PG::Result. So you will have to call ntuples on it so see how many rows are returned from the query.

so change your if clause to something like:

if users_name.ntuples > 0
  puts "There are users"
  puts "There is no users available in the table users"

See PG::Result's documentation to know what other methods you can call on it to access the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download