【问题标题】:storing 3 values in MYSQL在 MYSQL 中存储 3 个值
【发布时间】:2016-03-18 10:43:53
【问题描述】:

我的问题是我创建了一个数学测验,它会询问用户 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,name,score1,score2,score3 当我完成测验时,分数、姓名和 ID 将被输入到表格中。但是一旦具有相同 ID 的用户进行测验,就会出现错误。我希望代码为每个用户存储 3 个分数,但出现错误.错误是:

cursor.execute(add_record, data_record) NameError: name 'add_record' 没有定义

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

【问题讨论】:

  • 然后标记php在这里做什么?
  • 抱歉 id 不是要添加的意思
  • 我删除了我的帖子,因为它不正确。不过,正如我在 cmets 中所说的那样。只需在 Python 环境 "ID" in "Class1" 中运行它...它将返回 False"score" in "Score1""score" in "Score2" 也是如此...您的问题是 none 您的 if 语句正在输入。除非您提及您希望这些行做什么,否则没有人可以提供帮助。
  • 我想要做的是为我的数据库添加一个分数。例如,我创建了这段代码,它将输入用户 ID、姓名和第一个分数到数据库。但我需要一段代码将为用户添加第二个分数。因此它将显示他们的第一个分数和第二个分数和第三个分数。我不知道如何编码。我将 if 语句放在那里,因为我认为“如果 score1已填充然后将 sccore 输入 score2" 但这不起作用。
  • 好的。现在我明白了,暂时忘记数据库。没有它你能做到你刚才说的吗?

标签: python mysql


【解决方案1】:

好的,我们将以尽可能小的步骤逐步完成我的解决方案,以达到您的解决方案。注意:单个文件中的所有这些代码都适用于我。

首先,我使用 Python 在数据库中创建一个表。我不确定为什么您的 Average 列是 INT 类型,所以我改变了它。另外,为了简单起见,我的 ID 是一个 INT。

import mysql.connector
cnx = mysql.connector.connect(user='root', password='password',
                             host='localhost',
                             database='mydb')
cursor = cnx.cursor()
# cursor.execute("DROP TABLE IF EXISTS Class1")
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Class1
    ( ID INT PRIMARY KEY
    , Name VARCHAR(10) NOT NULL
    , Score1 INT
    , Score2 INT
    , Score3 INT
    , Average DECIMAL(9, 5)
    );
''')
cnx.commit()

接下来,我创建了一个 User 类,以保存所有重要信息并包含进出数据库的逻辑。这样,您只需要一个 User 对象和一个方法即可。这种方法优于您的多个 INSERT 查询。

class User:
    def __init__(self, _id, name, score1=None, score2=None, score3=None):
        self._id = _id
        self.name = name
        self.score1 = score1
        self.score2 = score2
        self.score3 = score3

    ''' set the score of the given or next available class '''
    def add_score(self, score, Class=None):
        if not Class or (Class < 0 or Class > 3):
            if all((self.score1, self.score2, self.score3)):
                return # can't update
            elif all((self.score1, self.score2)):
                Class = 3
            elif self.score1:
                Class = 2
            else:
                Class = 1

        if Class and 0 < Class <= 3: # if a position is given and valid
            setattr(self, 'score' + str(Class), score)

    def to_tuple(self):
        return (self._id, self.name, self.score1, self.score2, self.score3)

    ''' make it possible to see this object when printed '''
    def __repr__(self):
        return self.__class__.__name__+ str(self.to_tuple())

    ''' insert or update this user object in the database '''
    def insert_to_db(self, db):
        crsr = db.cursor()
        data = list(self.to_tuple())
        data.append(self.get_average_score())
        if User.get_by_id(self._id):
            data = data[1:]
            data.append(self._id)
            crsr.execute('''
                UPDATE Class1 SET
                    Name = %s,
                    Score1 = %s,
                    Score2 = %s,
                    Score3 = %s,
                    Average = %s
                WHERE ID = %s;
            ''', data)
        else:
            crsr.execute("INSERT INTO Class1 VALUES (%s,%s,%s,%s,%s,%s)", data)
        db.commit()
        crsr.close()

    @staticmethod
    def get_by_id(_id):
        cursor.execute("SELECT * FROM Class1 WHERE ID = %s", [_id])
        row = cursor.fetchone()
        return User.from_tuple(row)

    @staticmethod
    def get_by_name(name):
        cursor.execute("SELECT * FROM Class1 WHERE Name = %s", [name])
        row = cursor.fetchone()
        return User.from_tuple(row)

    ''' Get the average score from the object. No need to query the database '''
    def get_average_score(self):
        from statistics import mean
        scores = list(self.to_tuple())[2:4]
        scores = list(filter(None.__ne__, scores))
        return mean(scores) if len(scores) > 0 else 0

    @staticmethod
    def from_tuple(tup, min_elems=2, max_elems=6):
        user = None
        if tup:
            num_elems = len(tup)
            if num_elems < min_elems or num_elems > max_elems:
                raise Exception('invalid tuple given', tup)
            # know there is at least 2 elements here
            user = User(tup[0], tup[1])
            if num_elems >= 3:
                user.score1 = tup[2]
            if num_elems >= 4:
                user.score2 = tup[3]
            if num_elems >= 5:
                user.score3 = tup[4]
        return user

    @staticmethod
    def from_cursor(cursor):
        if cursor:
            return (User.from_tuple(row) for row in cursor.fetchall())
        return iter(()) # Return empty generator if cursor == None

接下来,定义一个测验方法,返回参加测验的人的分数和姓名。参数是可选的并且具有默认值。定义许多小方法以测试您的代码和逻辑是一个好习惯。

def quiz(num_questions=10, name=None):
    if not name:
        name = input("Enter your name: ").title()
    print(name, ", Welcome to the Maths Test")

    score = 0
    for _ in range(num_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")
    return name, score

最后(与您的其他方法一起),这是将与程序一起运行的主要方法。这会提示输入一个 ID,尝试在数据库中找到它,然后对现有用户进行测验并更新他们的分数,或者创建一个新用户,然后将用户插入数据库。

def main():
    user_id = get_int_input("Enter your ID: ")
    Class = get_int_input("Which class do you wish to input results for 1, 2, or 3? ")
    user = User.get_by_id(user_id)
    if not user:
        print("User with id %d not found" % user_id)
        print("Creating new user")
        name, score = quiz(NB_QUESTIONS)
        user = User(user_id, name)
    else:
        print("Found user %s" % user.name)
        _, score = quiz(NB_QUESTIONS, user)

    user.add_score(score, Class)
    print("\nWell done", user.name, "you scored", score, "/", NB_QUESTIONS)
    print("Thank you for doing this mathamatical quiz , goodbye ")

    user.insert_to_db(cnx) # Remember to update the user in the database
    cnx.close()

if __name__ == '__main__':
    main()

【讨论】:

  • 这不起作用。我没有收到错误,但我的数据库没有得到分数的第二个输入
  • 当您在“score1”中执行“score”时,您正在测试一个字符串是否是另一个字符串的一部分。你可以发布你的完整代码。
  • 你是什么意思,我真的被困在这个解决方案上。
  • 例如,“score”不在“Score1”中,因为“score”不是“Score1”的子字符串。同样,“ID”不是“Class1”的子字符串。根本不应该输入那些 if 语句。这真的是你写在代码中的内容吗?
  • 是的,因为我对这一切都很陌生,而且我还在学习。抱歉。你知道解决方案吗?
【解决方案2】:

如果“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()

cursor.close() cnx.close()

【讨论】:

  • 这不起作用。我没有收到错误,但我的数据库没有在列中获得第二个输入。
猜你喜欢
  • 2012-01-28
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 2018-06-14
  • 2010-10-11
  • 2012-11-26
  • 2012-12-18
  • 1970-01-01
相关资源
最近更新 更多