db_print.py 2.1 KB

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