2014-05-23 100 views
0

我正在創建一個基於Web的POS系統。一旦用戶點擊了「提交訂單」的數據通過該模式提出:多個sqlite3插入問題

CREATE TABLE orders (
    transaction_id integer primary key autoincrement, 
    total_price integer not null 
); 
CREATE TABLE order_items (
    transaction_id integer REFERENCES orders(transaction_id), 
    SKU integer not null, 
    product_name text not null, 
    unit_price integer not null, 
    quantity integer not null 
); 

通過這個燒瓶代碼:

@app.route('/load_ajax', methods=["GET", "POST"]) 
def load_ajax(): 
    if request.method == "POST": 
     data = request.get_json() 
     for group in groupby(data, itemgetter('name')): 
      id, data_list = group 
      for d in data_list: 
       print d['subtotal'] 
       db = get_db() 
       db.execute('insert into order_items (SKU, product_name, unit_price, quantity) values (?, ?, ?, ?); insert into orders (total_price) values (?)', 
       [d['sku'], d['name'], d['price'], d['quantity']],[d['subtotal']]) 
       db.commit() 
     return jsonify(location=url_for('thankyou')) 

我得到一個500錯誤,我不知道爲什麼它是發生。我需要做兩個不同的db.execute語句嗎?

+1

我建議考慮看看瓶,SQLAlchemy的。您不必在代碼中編寫像這樣的SQL查詢。 – IanAuld

+0

謝謝,會做。 – metersk

+1

http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html#a-minimal-application – IanAuld

回答

2

是的,您需要使用兩個不同的.execute()語句。引用cursor.execute() documentation

​​只會執行一條SQL語句。

所以這樣做:

db.execute('insert into order_items (SKU, product_name, unit_price, quantity) values (?, ?, ?, ?)', 
      (d['sku'], d['name'], d['price'], d['quantity'])) 
db.execute('insert into orders (total_price) values (?)', 
      (d['subtotal'],))