def save_to_navicat(comments): connection = pymysql.connect( host='localhost', user='root', password='123456', database='demo', charset='utf8' ) try: with connection.cursor() as cursor: sql = "INSERT INTO `user` (`content`) VALUES (%s)" cursor.execute(sql, (comments,)) connection.commit() finally: connection.close(),解决报错,Traceback (most recent call last): File "C:\Users\鲸阿丫丫\Desktop\爬虫\1.py", line 59, in <module> save_to_navicat(comments) File "C:\Users\鲸阿丫丫\Desktop\爬虫\1.py", line 46, in save_to_navicat cursor.execute(sql, (comments,))
时间: 2024-03-22 12:39:25 浏览: 73
这个错误可能是由于参数传递不正确导致的。请确保 `comments` 参数是一个字符串类型,否则请将其转换为字符串。另外,你可以尝试使用 `try...except` 语句来捕获异常,以便更好地调试和排除问题。你可以尝试修改代码如下:
```
def save_to_navicat(comments):
connection = pymysql.connect(
host='localhost',
user='root',
password='123456',
database='demo',
charset='utf8'
)
try:
with connection.cursor() as cursor:
sql = "INSERT INTO `user` (`content`) VALUES (%s)"
cursor.execute(sql, (str(comments),))
connection.commit()
except Exception as e:
print(e)
finally:
connection.close()
```
注意,在上面的代码中,我们在执行 `cursor.execute` 语句时将 `comments` 参数强制转换为字符串类型,以确保它是一个有效的字符串。另外,我们还添加了一个 `try...except` 语句以捕获可能发生的异常,并将异常信息打印出来,以便更好地调试和排除问题。
阅读全文