[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

cmdargs = sys.argv[1:]
if '-' in cmdargs: # format if '-' in cmdline args
format = True # dbname if other cmdline arg
cmdargs.remove('-')
if cmdargs: dbname = cmdargs.pop(0)
if cmdargs: table = cmdargs[0]


from loaddb import login
conn, curs = login(dbname)
dumpdb(curs, table, format)


While we’re at it, let’s code some utility scripts to initialize and erase the database, so
we do not have to type these by hand at the interactive prompt again every time we
want to start from scratch. Example 17-11 completely deletes and re-creates the data-
base, to reset it to an initial state (we did this manually at the start of the tutorial).


Example 17-11. PP4E\Dbase\Sql\makedb.py


"""
physically delete and re-create database files
usage: makedb.py dbname? tablename?
"""


import sys
if input('Are you sure?').lower() not in ('y', 'yes'):
sys.exit()


dbname = (len(sys.argv) > 1 and sys.argv[1]) or 'dbase1'
table = (len(sys.argv) > 2 and sys.argv[2]) or 'people'


from loaddb import login
conn, curs = login(dbname)
try:
curs.execute('drop table ' + table)
except:
print('database table did not exist')


command = 'create table %s (name char(30), job char(10), pay int(4))' % table
curs.execute(command)
conn.commit() # commit may be optional here
print('made', dbname, table)


Next, the clear script in Example 17-12 deletes all rows in the table, instead of dropping
and re-creating them entirely. For testing purposes, either approach is sufficient. Minor
caveat: the rowcount attribute doesn’t always reflect the number of rows deleted in
SQLite; see its library manual entry for details.


Example 17-12. PP4E\Dbase\Sql\cleardb.py


"""
delete all rows in table, but don't drop the table or database it is in
usage: cleardb.py dbname? tablename?
"""


1350 | Chapter 17: Databases and Persistence

Free download pdf