2014-08-31 67 views
1

我想記錄表單數據並將其傳遞到另一個頁面,所以我只是要傳遞它(自動增量)行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') 

此外,有沒有更好的方法來做到這一點?

回答

2

您嘗試從全新的光標獲取值。你想用你從中獲得值的同一個遊標來執行你的插入。

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

相關問題