2016-03-08 69 views
1

必須有更好的方法來做到這一點..我已經閱讀了瓶子文檔,但它並沒有真正幫助那麼多。這工作,但它很髒。似乎我錯過了一些東西。插入表單字段到數據庫(Bottle,sqlite)

@route('/client/new', method="POST") 
def add_new_client(): 
    c = db.cursor() 
    query = """INSERT INTO Clients VALUES(NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""" 

    try: 
     r = request.POST 

     d = r['LastContact'].split('/') # mm/dd/yyyy 
     try: lastcontact = datetime(int(d[2]), int(d[0]), int(d[1])) 
     except Exception as e: lastcontact = datetime.now() 

     try: taxExempt = r['TaxExempt'] 
     except Exception as e: taxExempt = 0 

     c.execute(query, (r['FirstName'], r['LastName'], r['Address1'], r['Address2'], r['City'], r['State'], r['Zip'], 
       r['HomePhone'], r['CellPhone'], r['WorkPhone'], r['Email'], r['ContactMethod'], r['ContactTime'], 
       r['ContactFrequency'], lastcontact, taxExempt, r['TaxID'], r['Notes'])) 
     db.commit() 
    except Exception as e: 
     print "ERROR %s" % e 
    redirect('/client/%d' % c.lastrowid) 
    c.close() 

回答

1

事情會看起來更乾淨,如果你會使用SQLAlchemy ORM,相關文章:

如果你想留在混合SQL和Python,可以簡化代碼通過使用命名/關鍵字查詢佔位符這將允許您只需將r字典傳入查詢:

d = r['LastContact'].split('/') # mm/dd/yyyy 
try: 
    r['LastContact'] = datetime(int(d[2]), int(d[0]), int(d[1])) 
except Exception as e: 
    r['LastContact'] = datetime.now() 

if 'TaxExempt' not in r: 
    r['TaxExempt'] = 0 

query = """ 
    INSERT INTO 
     Clients 
    VALUES 
     (NULL, 
     :FirstName, 
     :LastName, 
     :Address1, 
     :Address2, 
     :City, 
     :State, 
     :Zip, 
     :HomePhone, 
     :CellPhone, 
     :WorkPhone, 
     :Email, 
     :ContactMethod, 
     :ContactFrequency, 
     :ContactTime, 
     :LastContact, 
     :TaxExempt, 
     :TaxID, 
     :Notes) 
""" 
c.execute(query, r) 
+0

不知道它命名佔位符。這有助於我弄清楚如何使用sqlalchemy。鍊金術似乎比sqlite3好多了。謝謝! – Bocochoco