python - 如何使用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
解决方案
如您收到的错误所示,您的 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 表的整个过程。为什么将您的执行语句声明为变量?
希望这可以帮助!
推荐阅读
- python - Django为models.ForeignKey生成太多SQL查询
- xml - xmlstarlet 根据属性选择值
- tensorflow - BERT 调用函数中的关键字参数
- python - 如何使用 matplotlib 更改 y 刻度?
- c++ - 如何将映射键更改为值并将值更改为键?
- r - R - 加权计数
- dns - 如何在 docker-compose 中配置 dns-proxy-server 以绑定到非默认 IP 地址
- signal-processing - 如何计算 3D 空间(X、Y、T)中时间序列的 FFT
- android - 在路径上移动项目
- ios - ODR 异常“NSBundleResourceRequest 无法连接到它的辅助守护程序”