gpt4 book ai didi

python - 在MYSQL中存储3个值

转载 作者:行者123 更新时间:2023-11-29 21:43:51 25 4
gpt4 key购买 nike

我的问题是我创建了一个数学测验,该测验将询问用户 10 个随机问题,然后最终输出他们的分数(满分 10 分)。我已经完成了这项任务的艺术,但我对最后一部分感到挣扎最后一部分是我需要创建一些东西来存储每个用户的最后 3 个分数。我决定使用 mysql,但我的代码只会让我为每个用户存储 1 个分数。我使用 python 3.4。这是代码.

import random
import operator
import mysql.connector
cnx = mysql.connector.connect(user='root', password='password',
host='localhost',
database='mydb')

cursor = cnx.cursor()


ID = input("what is your ID?")


OPERATIONS = [
(operator.add, "+"),
(operator.mul, "x"),
(operator.sub, "-")
]

NB_QUESTIONS = 10

def get_int_input(prompt=''):
while True:
try:
return int(input(prompt))
except ValueError:
print("Sorry,but we need a number")

if __name__ == '__main__':
name = input("What is your name?").title()
Class=input("Which class do you wish to input results for 1,2 or 3?")
print(name, ", Welcome to the Maths Test")

score = 0
for _ in range(NB_QUESTIONS):
num1 = random.randint(1,10)
num2 = random.randint(1,10)
op, symbol = random.choice(OPERATIONS)
print("What is", num1, symbol, num2)
if get_int_input() == op(num1, num2):
print("Correct")
score += 1
else:
print("Incorrect")

print("Well done", name, "you scored", score, "/", NB_QUESTIONS)

print ("Thank you for doing this mathamatical quiz , goodbye ")


if "ID" in "Class1":
if "score" in "Score1":
add_record = ("INSERT INTO Class1"
"(Score2)"
"VALUES(%s)")
data_record = (score)


if "score" in "Score2":
add_record = ("INSERT INTO Class1"
"(Score3)"
"VALUES(%s)")
data_record = (score)

else:
add_record = ("INSERT INTO Class1"
"(ID, Name, Score1) "
"VALUES (%s, %s, %s)")
data_record = (ID, name, score)

cursor.execute(add_record, data_record)
cnx.commit()

cursor.close()
cnx.close()

在我的数据库中,我有列 ID、名称、score1、score2、score3当我完成测验时,分数、姓名和 ID 将被输入到表中。但是一旦具有相同 ID 的用户进行测验,就会出现错误。我希望代码为每个用户存储 3 个分数,但出现错误.错误是:

cursor.execute(add_record, data_record)NameError:名称“add_record”未定义

感谢您阅读本文,也感谢您的帮助。我期待听到您的回复。

最佳答案

如果“ID”在“Class1”中:

if "score"  in "Score1":
add_record = ("INSERT INTO Class1"
"(Score2)"
"VALUES(%s)")
data_record = (score)

if "score" in "Score2":
add_record = ("INSERT INTO Class1"
"(Score3)"
"VALUES(%s)")
data_record = (score)

else:
add_record = ("INSERT INTO Class1"
"(ID, Name, Score1) "
"VALUES (%s, %s, %s)")
data_record = (ID, name, score)
cursor.execute(add_record, data_record)
cnx.commit()

光标.close()cnx.close()

关于python - 在MYSQL中存储3个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com