/Doc/includes/sqlite3/simple_tableprinter.py

http://unladen-swallow.googlecode.com/ · Python · 26 lines · 17 code · 6 blank · 3 comment · 3 complexity · 3007cb9f0958b7bc9e7ea3b2bd31d842 MD5 · raw file

  1. import sqlite3
  2. FIELD_MAX_WIDTH = 20
  3. TABLE_NAME = 'people'
  4. SELECT = 'select * from %s order by age, name_last' % TABLE_NAME
  5. con = sqlite3.connect("mydb")
  6. cur = con.cursor()
  7. cur.execute(SELECT)
  8. # Print a header.
  9. for fieldDesc in cur.description:
  10. print fieldDesc[0].ljust(FIELD_MAX_WIDTH) ,
  11. print # Finish the header with a newline.
  12. print '-' * 78
  13. # For each row, print the value of each field left-justified within
  14. # the maximum possible width of that field.
  15. fieldIndices = range(len(cur.description))
  16. for row in cur:
  17. for fieldIndex in fieldIndices:
  18. fieldValue = str(row[fieldIndex])
  19. print fieldValue.ljust(FIELD_MAX_WIDTH) ,
  20. print # Finish the row with a newline.