I am learning the database operations in ruby. I was experimenting the database operations.
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 "There is no users available in the table users"
rescue PG::Error => e
db_con.close if db_con
users_name = db_con.exec_prepared 'get_result' will never return
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
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" else puts "There is no users available in the table users" end
PG::Result's documentation to know what other methods you can call on it to access the result.