首页 > 解决方案 > 尽管在数据库中添加了行,但 SQL 查询在点击后退按钮后不会返回新添加的行

问题描述

我有一个烧瓶应用程序,它有一个注册表单,将数据添加到将数据添加到 SQLite 数据库POST的视图中。registration.py每次注册时,都会在数据库中插入一个新行。

预计会发生什么:

提交表单后,如果用户点击浏览器中的后退按钮并尝试再次提交表单,下面的代码应该是

  1. try检查电子邮件是否存在
  2. 如果exception(电子邮件不存在)插入数据

问题:

当用户点击后退按钮并再次提交表单时,try块中的代码无法识别先前(在点击后退按钮之前)添加的行。选择查询失败。

甚至更奇怪的事情:

但是,当我只是在try块之前打印出数据库中的所有行时,这显示了email刚刚添加的行。选择查询虽然没有看到它。

Registration.py问题块

    db = get_db()

    # Dumping to log to check if the db actually has the row
    cur_e = db.execute('SELECT user_id, user_email FROM cld_user')
    ie = cur_e.fetchall()
    for i in ie:
        print "ID: {} | Email: {}".format(i[0], i[1])
    print "end of ID dump" 
    print user_email
    # The above code does print out the row (even after hitting the back button)

    try:
        # This block however, fails when user submits the form after hitting the back button
        print "Trying"
        cur_ps = db.execute('SELECT user_id, user_uid FROM cld_user \
            WHERE user_email = ?', [user_email])
        user_id = cur_ps.fetchone()[0]
        user_uid = cur_ps.fetchone()[1]
        print "Row exists"
        flash(user_id, "success")

    except Exception:
        print "Exception"
        cur_p = db.execute('INSERT OR IGNORE INTO cld_user \
            (user_uid, user_name, user_email, user_contact) \
            VALUES (?, ?, ?, ?)', [user_uid, user_name, 
            user_email, user_contact])
        user_id = cur_p.lastrowid
        print "No row exists"
        flash(user_id, "success")

标签: pythonsqliteflask

解决方案


try总是失败。user_uid = cur_ps.fetchone()[0]如果查询没有返回任何行,它将在这一行失败。user_uid = cur_ps.fetchone()[1]如果查询返回一行,它将在这一行失败。

fetchone 一次返回一行。此行user_id = cur_ps.fetchone()[0]正在查找返回的列表中的元素 0 fetchone。如果没有匹配 user_email 的行,它会失败并显示“None type object not subscriptable”,因此执行except

如果返回一行,控制移至该行user_uid = cur_ps.fetchone()[1]。如果查询返回 2 行或更多行,则此行将成功。如果它只返回 1 行,则该行将失败,因为结果fetchone为 None,它会给出“None type object is not subscriptable”。

关于可能的更正:将一个变量设置为 的结果fetchone,例如row = cur_ps.fetchone(),然后将其他变量分别设置为row[0]row[1]


推荐阅读