如何使用Python将记录添加到MySQL中具有两个字段的表中?

2024-03-29 08:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我的数据库中有一个名为user_attempts的表,它只有两个字段:username和attemptID。AttemptID是由数据库自动生成的,因此,当我添加记录时,我不必为AttemptID传入一个值,而只为username传入一个值。这是我目前拥有的代码:

mycursor= mydb.cursor()
username='test'
mycursor.execute('INSERT INTO user_attempt(username) VALUE(%s)',username)
mydb.commit()

我不明白为什么这个SQL命令不起作用,因为当我直接在MySQL工作台中键入它时,它工作得非常好,只是在python中似乎不起作用。我已经正确连接了数据库,因为代码中的其他SQL命令工作得非常好。这是我得到的错误:

  File "C:\Users\User\Desktop\project\AA game things\Iteration 1\review.py", line 132, in reviewPage
    add_userattempt=mycursor.execute('INSERT INTO user_attempt(username) VALUE(%s)',(str(username)))
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 590, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 478, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1