我不知道如何改进此代码,我正在尝试使用具有不同值的相同字段插入多个数据。有人可以改进我的代码吗?
<form action="/submits/ method="POST">
<input type="text" name="book" value="Divergent">
<input type="text" name="author" value="Veronica Roth">
<input type="text" name="book" value="Allegiant">
<input type="text" name="author" value="Veronica Roth">
<input type="text" name="book" value="Inferno">
<input type="text" name="author" value="Dan Brown">
<input type="submit" value="Submit">
</form>
@app.route('/submits/', methods = ['POST'])
def books():
if method == "POST":
BOOK = request.form['book']
AUTHOR = request.form['author']
stmt = "INSERT INTO shelf (book_column, author_column) VALUES (%s, %s)"
c.executemany(stmt, (BOOK, AUTHOR))
conn.commit()
答案 0 :(得分:1)
您可以尝试使用getlist
:
if method == "POST":
stmt = "INSERT INTO shelf (book_column, author_column) VALUES (%s, %s)"
books = request.form.getlist('book')
authors = request.form.getlist('author')
for i, book in enumerate(books):
c.executemany(stmt, (book, authors[i]))
c.commit()