从查看代码来看,您似乎创建了错误的数据变量。
如果看这个例子:
names = ['peter', 'patty', 'micheal']
emails = ['example@gmail.com','test@gmail.com','foo@gmail.com']
passwords = ['asghgshsdgds','123','aasasa']
data =[names, emails, passwords]
print(data)
#[['peter', 'patty', 'micheal'],['example@gmail.com', 'test@gmail.com', 'foo@gmail.com'], ['asghgshsdgds', '123', 'aasasa']]
在哪里做类似的事情:
data = list()
if len(names) == len(emails) == len(passwords):
for i, val in enumerate(names):
data.append([names[i], emails[i], passwords[i]])
print(data)
# [['peter', 'example@gmail.com', 'asghgshsdgds'], ['patty', 'test@gmail.com', '123'], ['micheal', 'foo@gmail.com', 'aasasa']]
这是我认为的主要问题。
所以解决方案是:
@app.route("/insert", methods=["POST", "GET"])
def insert():
cur = mysql.connection.cursor()
if request.method == 'POST':
names = request.form.getlist('name[]')
emails = request.form.getlist('email[]')
passwords = request.form.getlist('passwprd[]')
data = list()
if len(names) == len(emails) == len(passwords):
for i, val in enumerate(names):
data.append([names[i], emails[i], passwords[i]])
for value in data:
cur.executemany('INSERT INTO users (name, email, password) VALUES (%s, %s, %s)', [value])
mysql.connection.commit()
cur.close()
flash('New record created successfully')
return redirect('/')
编辑
经过进一步调查,我相信可以通过以下方式进一步简化:
@app.route("/insert", methods=["POST", "GET"])
def insert():
cur = mysql.connection.cursor()
if request.method == 'POST':
names = request.form.getlist('name[]')
emails = request.form.getlist('email[]')
passwords = request.form.getlist('passwprd[]')
data = list()
if len(names) == len(emails) == len(passwords):
for i, val in enumerate(names):
data.append([names[i], emails[i], passwords[i]])
stmt = 'INSERT INTO users (name, email, password) VALUES (%s, %s, %s)'
cursor.executemany(stmt, data)
mysql.connection.commit()
cur.close()
flash('New record created successfully')
return redirect('/')