【问题标题】:Why can't I get the database lastrowid?为什么我无法获取数据库 lastrowid?
【发布时间】:2014-10-25 02:18:59
【问题描述】:

我想记录表单数据并将其传递到另一个页面,所以我只是将(自动递增)行 id 传递给它,然后在下一个函数中检索它。它正在正确创建数据库条目,但光标lastrowid 总是返回None,所以我无法获取下一页的数据。

def connect_db():
    """Connects to the database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv


def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.route('/choose', methods=['GET', 'POST'])
def input_values():
    form = UserValuesForm()
    if form.validate_on_submit():
        g.db = get_db()
        g.db.execute('insert into requests (occupants, '
                   'transmission_type, drive_type, engine_type, fuel_economy, '
                   'trunk_capacity, towing_capacity, safety_rating) '
                   'values (?, ?, ?, ?, ?, ?, ?, ?)',
                   [form.occupants.data, ';'.join(form.transmission_type.data),
                    ';'.join(form.drive_type.data), ';'.join(form.engine_type.data),
                    form.fuel_economy.data, form.trunk_capacity.data,
                    form.towing_capacity.data, form.safety_rating.data])
        g.last_req_id = g.db.cursor().lastrowid
        g.db.commit()
        return redirect('results/{0}'.format(str(g.last_req_id)))
    return render_template('choose.html', form=form)

@app.route('/results/<int:req_id>', methods=['GET'])
def result(req_id):
    return render_template('results.html')

另外,有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python python-3.x sqlite flask flask-wtforms


    【解决方案1】:

    您尝试从全新的光标中获取值。您想使用您从中获取值的相同光标执行插入。

    cursor = g.db.cursor()
    cursor.execute('...')
    g.last_req_id = cursor.lastrowid
    g.db.commit()
    

    此外,您无需将last_req_idg 关联,因为您只需在input_values 中本地使用它。

    last_req_id = cursor.lastrowid
    return redirect('results/{0}'.format(last_req_id))
    

    您还会看到我删除了对str 的调用。 format 将为您处理。

    【讨论】:

    • 除非它在 ​​Python 的绑定中受到限制,否则最后一行 id 在提交之前确实是可用的。
    • @ColonelThirtyTwo 你是对的。谢谢。修复帖子。
    • 非常感谢!我很困惑,因为数据库连接 g.db 具有创建条目所需的执行方法,所以我没有意识到我需要显式创建游标对象。
    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2019-02-13
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多