为什么我无法获得数据库lastrowid?

问题描述:

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

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') 

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

您尝试从全新的光标获取值。你想用你从中获得值的同一个游标来执行你的插入。

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)) 

您还会看到我删除调用strformat将为您处理。

+0

除非它对Python的绑定有限制,否则在提交之前最后一行ID确实可用。 – 2014-09-01 01:39:37

+0

@ColonelThirtyTwo你是对的。谢谢。修复帖子。 – dirn 2014-09-01 01:52:12

+0

非常感谢!我很困惑,因为数据库连接g.db有我需要的一个条目执行方法,所以我没有意识到我需要显式创建游标对象。 – zomp 2014-09-01 02:48:20