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