我正在尝试从HTML
表单中获取用户输入,并将其存储到SQlite3
数据库中。
HTML表单具有1个单选按钮集(具有4个选择)和7个文本输入。看起来像这样(没有所有格式):
<input type="radio" name="ProducteurType" value="Prod" checked="checked">
<input type="radio" name="ProducteurType" value="Coll">
<input type="radio" name="ProducteurType" value="Traitement">
<input type="radio" name="ProducteurType" value="Autre">
<input type="text" name="ProducteurSIRET">
<input type="text" name="ProducteurNOM">
<input type="text" name="ProducteurAdresse">
<input type="text" name="ProducteurTel">
<input type="text" name="ProducteurFax">
<input type="text" name="ProducteurCourriel">
<input type="text" name="ProducteurContact">
我使用以下代码将这些输入存储到数据库中:
@post('/ajoutClient')
def ajoutClient():
conn = sqlite3.connect('db/bsd.db')
create_if_need = """CREATE TABLE IF NOT EXISTS Clients (id INTEGER PRIMARY KEY AUTOINCREMENT,
ProducteurType TEXT,
ProducteurSIRET TEXT,
ProducteurNOM TEXT,
ProducteurAdresse TEXT,
ProducteurTel TEXT,
ProducteurFax TEXT,
ProducteurCourriel TEXT,
ProducteurContact TEXT)"""
conn.execute(create_if_need)
rf = request.forms
insert_client_query = """
INSERT INTO
Clients(ProducteurType,ProducteurSIRET,ProducteurNOM,ProducteurAdresse,ProducteurTel,ProducteurFax,ProducteurCourriel,ProducteurContact)
VALUES (?,?,?,?,?,?,?,?)"""
conn.execute(insert_client_query,rf)
conn.commit
我收到以下错误:
File "/usr/lib/python3/dist-packages/bottle.py", line 1826, in __getitem__ def __getitem__(self, key): return self.dict[key][-1] KeyError: 0
我知道“ KeyError 0”意味着以某种方式,我给数据库提供了太多或不足的字段。
我已经填写了表格中的所有字段,因此没有空值。 我已经检查了字段的数量:表单和数据库中都有8个字段。 我已经检查了字段名称:它们是相同的。
我对“ id”主键做错了吗? HTML“ radio”输入与数据库插入不兼容,还是我应该将其存储为4个布尔值(一个为true,其他三个为false)?
答案 0 :(得分:0)
好吧,我明白了。我严重使用了request.forms字典。这段代码有效:
rf = request.forms
conn.execute('INSERT INTO Clients values (NULL,?,?,?,?,?,?,?,?)', [\
rf['ProducteurType'],\
rf['ProducteurSIRET'],\
rf['ProducteurNOM'],\
rf['ProducteurAdresse'],\
rf['ProducteurTel'],\
rf['ProducteurFax'],\
rf['ProducteurCourriel'],\
rf['ProducteurContact'] ])
conn.commit