Python - for循环退出 'prematurely'

标签 python for-loop sqlite

编辑: 回答:我需要为“einlesen()”函数创建另一个游标。

这是我第一次在 Python 中使用 SQLite3,所以请原谅我(也许)糟糕的语法;) 我正在尝试构建一种 DVD 数据库,它直接从亚马逊获取必要的信息( Actor 等)。整个程序基于SQLite3和Python 2.7。

一切正常,除了我的计划“更新”功能。

def update():
    print 'Update Datenbank....bitte warten....'
    cursor.execute('''SELECT titel, amazon, erhalten, ausgeliehen FROM movies''')
    antwort = 'update'
    for row in cursor:
        stelle = row[1]
        ausg = row[2]
        erh = row[3]
        einlesen(stelle, ausg, erh, antwort)
        print row[0]
    raw_input('Update komplett!')
    menu()

问题是,循环在一次迭代后退出。

输出如下所示:

Update Datenbank....bitte warten....
#a few seconds pass
The Day After Tommorrow
Update komplett!

所以我看到,循环和函数调用是正确的(数据库得到正确更新 - 由函数“einlesen()”完成),但是还有更多迭代,而不仅仅是一次...... 所以我的问题是:出了什么问题? ;)

这是(缩写)“einlesen()”函数:

def einlesen(asin, ausg, erh, antwort):
    d = {}
    infos = urllib.urlopen('http://www.amazon.de/dp/'+asin).read()
    titel = infos[infos.find('Kaufen Sie')+11:infos.find('nstig ein')-3]
    art = 'dvd'
    infos = remove_html_tags(infos)
    infos = infos[infos.find('Darsteller: '):infos.find('Durchschnittliche')]
    infos = infos.split('\n')
    for x in range(200):
        try:
            infos.remove('')
        except:
            break
    for element in infos:
            d[element.split(': ')[0].lstrip()] = element.split(': ')[1]

#(excluded the whole Info-Scraping process)

    if antwort == 'update':
        movie = dauer, art, regie, jahr, fsk, darsteller, titel
        sql = ('''UPDATE movies SET laufzeit = ?, art = ?, regie = ?, jahr = ?, fsk =     ?, darsteller = ? WHERE titel = ?''')
        cursor.execute(sql, movie)
        connection.commit()
    else:
        menu()

感谢您的帮助。

最佳答案

当您仍在循环SELECT的结果时,您执行了UPDATE。这会删除第一个 cursor.execute() 的结果。

使用第二个光标。

编辑:

cur1 = con.cursor()
cur2 = con.cursor()

cur1.execute("SELECT ...")
for row in cur1:
    cur2.execute("UPDATE ...")

关于Python - for循环退出 'prematurely',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258983/

相关文章:

python - 以编程方式按下工具栏上的 `X` 按钮?

python - 是否可以在 jupyter 中重定向单元格输出

python - Microsoft 学术知识 API 缺少信息

python - 获取 "sqlite3.OperationalError: no such column:"

python - 如何在 wx.html.htmlwindow 中获取字符串选择

java - For 循环条件约定

javascript - 使用 .html() 清除以前的随机字符串不起作用

for-loop - 当 delim 为 ',' 时,批处理脚本会跳过 .CSV 中的空白条目

java - 从对象获取值

python - 如何使用python 3解密SQLite数据库中的项目