必须有一个更好的方法来做到这一点..我已经阅读了瓶子文档,但它并没有真正帮助那么多。这很有效,但很脏。好像我错过了什么。
@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()
答案 0 :(得分: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)