suresh suresh - 1 year ago 105
Ruby Question

Why does this code not give expected output?

I was experimenting with 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
contains only two columns. They are,


If the table does not contain any row, the
statement does not return any row. In this case, why does the if condition not become false? How do I check if the
method doesn't return any row?

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