Posted By

plexus on 06/08/07


Tagged

database ruby irb DBI


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


formatted output of DBI result set


 / Published in: Ruby
 

Sometimes I use irb as my database console, DBI is really handy for talking to different db's. Pass this method the result of conn.execute to get it nicely formatted on your screen. (it's a hack, should be more DRY)

  1. def form(re)
  2. re.each do |r|
  3. i,cols,vals = 0,'|','|'
  4. r.column_names.each do |n|
  5. cols << "%-20s|" % n
  6. vals << "%-20s|" % r[n].to_s[0..19]
  7.  
  8. if ((i+=1) == 5)
  9. puts cols
  10. puts "+" + (("%s+" % (" "*20))*5)
  11. puts vals
  12. puts "+" + (("%s+" % ("="*20))*5)
  13. i,cols,vals = 0,'|','|'
  14. end
  15. end
  16. puts cols
  17. puts "+" + (("%s+" % (" "*20))*5)
  18. puts vals
  19. puts "+" + (("%s+" % ("="*20))*5)
  20. puts "+"*106
  21. end
  22. end
  23.  
  24. conn=DBI.connect('DBI:....', 'uname', 'pwd')
  25. form(conn.execute('select * from table')

Report this snippet  

You need to login to post a comment.