首页 > 解决方案 > 如何使用python将记录添加到MySQL中的表中?

问题描述

在我的代码中,我试图将数据插入到我的数据库的“user_attempts”表中,该表有两个字段:attemptID(自动递增)和用户名。因此,当我传递数据时,我只需要传递用户名,因为 tryID 是由 MySQL 生成的。这是我的代码:

username='test1'
add_userattempt=mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})
mydb.commit()

但是它返回此错误:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\project\AA game things\Iteration 1\review.py", line 266, in <module>
    reviewPage(screen) # the home screen function is called which essentially starts the whole program.
  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) VALUES %(currentuser)s', {'currentuser' :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 ''test1'' at line 1

标签: pythonmysqldatabase

解决方案


如您收到的错误所示,您的 SQL 代码中有语法错误。代替

mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})

它应该是

mycursor.execute('INSERT INTO user_attempt(username) VALUES(%s)', username)

这个网页(https://www.mysqltutorial.org/python-mysql-insert/)很好地解释了使用 python 将数据插入 MySQL 表的整个过程。为什么将您的执行语句声明为变量?

希望这可以帮助!


推荐阅读