db_print.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """ db_print.py -- a simple demo for ADO database reads."""
  2. from __future__ import with_statement #needed for Python 2.5
  3. import sys
  4. import adodbapi.ado_consts as adc
  5. cmd_args = ('filename', 'table_name')
  6. if 'help' in sys.argv:
  7. print('possible settings keywords are:',cmd_args)
  8. sys.exit()
  9. kw_args = {} # pick up filename and proxy address from command line (optionally)
  10. for arg in sys.argv:
  11. s = arg.split("=")
  12. if len(s) > 1:
  13. if s[0] in cmd_args:
  14. kw_args[s[0]] = s[1]
  15. kw_args.setdefault('filename', "test.mdb") # assumes server is running from examples folder
  16. kw_args.setdefault('table_name', 'Products') # the name of the demo table
  17. # the server needs to select the provider based on his Python installation
  18. provider_switch = ['provider', 'Microsoft.ACE.OLEDB.12.0', "Microsoft.Jet.OLEDB.4.0"]
  19. # ------------------------ START HERE -------------------------------------
  20. #create the connection
  21. constr = "Provider=%(provider)s;Data Source=%(filename)s"
  22. import adodbapi as db
  23. con = db.connect(constr, kw_args, macro_is64bit=provider_switch)
  24. if kw_args['table_name'] == '?':
  25. print('The tables in your database are:')
  26. for name in con.get_table_names():
  27. print(name)
  28. else:
  29. #make a cursor on the connection
  30. with con.cursor() as c:
  31. #run an SQL statement on the cursor
  32. sql = 'select * from %s' % kw_args['table_name']
  33. print('performing query="%s"' % sql)
  34. c.execute(sql)
  35. #check the results
  36. print('result rowcount shows as= %d. (Note: -1 means "not known")' \
  37. % (c.rowcount,))
  38. print('')
  39. print('result data description is:')
  40. print(' NAME Type DispSize IntrnlSz Prec Scale Null?')
  41. for d in c.description:
  42. print(('%16s %-12s %8s %8d %4d %5d %s') % \
  43. (d[0], adc.adTypeNames[d[1]], d[2], d[3], d[4],d[5], bool(d[6])))
  44. print('')
  45. print('str() of first five records are...')
  46. #get the results
  47. db = c.fetchmany(5)
  48. #print them
  49. for rec in db:
  50. print(rec)
  51. print('')
  52. print('repr() of next row is...')
  53. print(repr(c.fetchone()))
  54. print('')
  55. con.close()