try: with connection.cursor() as cursor: sql = "INSERT INTO `comments` (`content`) VALUES (%s)" cursor.execute(sql, (comments)) connection.commit() finally: connection.close(),解决报错TypeError: not all arguments converted during string formatting
时间: 2024-02-14 14:16:00 浏览: 25
在执行 SQL 语句时,需要将参数传递给 execute 方法,通常是以元组或列表的方式传递。在你的代码中,传递给 execute 方法的参数是 `(comments)`,看起来是一个字符串类型的变量,但是由于它被括号包裹,所以实际上是一个单独的变量,而不是一个元组或列表。因此,在执行 SQL 语句时就会出现类型错误。
要解决这个问题,你需要将 `(comments)` 转换为一个元组或列表,例如将其括号去掉,改为 `comments,`(注意后面的逗号),这样就可以正确地传递参数给 execute 方法了。修改后的代码如下:
```
try:
with connection.cursor() as cursor:
sql = "INSERT INTO `comments` (`content`) VALUES (%s)"
cursor.execute(sql, (comments,))
connection.commit()
finally:
connection.close()
```
这样就可以正确地将评论内容插入到数据库中了。