Python游标重置函数 python重新定义运算符( 七 )


cursor.execute("UPDATE dvds SET title=:title, year=:year,"
"duration=:duration, director_id=:directorjd "
"WHERE id=:identity", locals())
db.commit()
要编辑DVD记录,我们必须首先找到用户需要操纵的记录 。如果找到了某个记录,我们就给用户修改其标题的机会,之后取回该记录的其他字段,以便将现有值作为默认值,将用户的输入工作最小化 , 用户只需要按Enter键就可以接受默认值 。这里,我们使用了命名的占位符(形式为:name),并且必须使用映射来提供相应的值 。对SELECT语句,我们使用一个新创建的字典;对UPDATE语句,我们使用的是由 locals()返回的字典 。
我们可以同时为这两个语句都使用新字典,这种情况下,对UPDATE语句,我们可以传递 dict(title=title, year=year, duration=duration, director_id=director_id, id=identity)) , 而非 locals() 。
在具备所有字段并且用户已经输入了需要做的改变之后,我们取回相应的发行者ID (如果必要就插入新的发行者记录),之后使用新数据对数据库进行更新 。我们采用了一种简化的方法,对记录的所有字段进行更新,而不仅仅是那些做了修改的字段 。
在使用DBM文件时,DVD标题被用作键,因此,如果标题进行了修改,我们就需要创建一个新的键-值项,并删除原始项 。不过 , 这里每个DVD记录都有一个唯一性的ID,该ID是记录初次插入时创建的 , 因此,我们只需要改变任何其他字段的值,而不需要其他操作 。
def find_dvd(db, message):
message = "(Start of) title to " + message
cursor = db.cursor()
while True: .
start = Console.get_stnng(message, "title")
if not start:
return (None, None)
cursor.execute("SELECT title, id FROM dvds "
"WHERE title LIKE ? ORDER BY title”,
(start +"%",))
records = cursor.fetchall()
if len(records) == 0:
print("There are no dvds starting with", start)
continue
elif len(records) == 1:
return records[0]
elif len(records)DISPLAY_LIMIT:
print("Too many dvds ({0}) start with {1}; try entering "
"more of the title".format(len(records),start))
continue
else:
for i, record in enumerate(records):
print("{0}:{1}".format(i + 1, record[0]))
which = Console.get_integer("Number (or 0 to cancel)",
"number", minimum=1, maximum=len(records))
return records[which -1] if which != 0 else (None, None)
这一函数的功能与dvdsdbm.py程序中的find_dvd()函数相同,并返回一个二元组 (DVD标题,DVD ID)或(None, None),具体依赖于是否找到了某个记录 。这里并不需要在所有数据上进行迭代,而是使用SQL通配符(%),因此只取回相关的记录 。
由于我们希望匹配的记录数较小,因此我们一次性将其都取回到序列的序列中 。如果有不止一个匹配的记录,但数量上又少到可以显示,我们就打印记录,并将每条记录附带一个数字编号,以便用户可以选择需要的记录,其方式与在dvds-dbm.py程序中所做的类似:
def list_dvds(db):
cursor = db.cursor()
sql = ("SELECT dvds.title, dvds.year, dvds.duration, "
"directors.name FROM dvds, directors "
"WHERE dvds.director_id = directors.id")
start = None
if dvd_count(db)DISPLAY_LIMIT:
start = Console.get_string("List those starting with [Enter=all]", "start")
sql += " AND dvds.title LIKE ?"
sql += ” ORDER BY dvds.title"
print()
if start is None:
cursor.execute(sql)
else:
cursor.execute(sql, (start +"%",))
for record in cursor:
print("{0[0]} ({0[1]}) {0[2]} minutes, by {0[3]}".format(record))
要列出每个DVD的详细资料,我们执行一个SELECT査询 。该査询连接两个表 , 如果记录(由dvd_count()函数返回)数量超过了显示限制值,就将第2个元素添加到WHERE 分支,之后执行该査询,并在结果上进行迭代 。每个记录都是一个序列,其字段是与 SELECT査询相匹配的 。