Scrapy 管道中MySQL数据库连接失败:AttributeError: 'NoneType' object has no attribute 'execute' 如何解决?

ID:20615 / 打印

scrapy 管道中mysql数据库连接失败:attributeerror: 'nonetype' object has no attribute 'execute' 如何解决?

scrapy 管道中使用 mysql 数据库

在使用 scrapy 管道存储数据到 mysql 数据库时,遇到错误的情况并不少见,这通常是由数据库连接问题引起的。下面将根据你的代码和遇到的错误,分析问题并给出解决方案。

代码中,你定义了两个管道:qiubaipropipeline 和 mysqlpipeline。

  • qiubaipropipeline 用于将数据写入文本文件。
  • mysqlpipeline 用于将数据写入 mysql 数据库。

你的错误信息显示“attributeerror: 'nonetype' object has no attribute 'execute'”。这表明在 mysqlpipeline 的 process_item 方法中,你尝试使用 self.cursor 执行查询,但 self.cursor 为空。

经过分析,问题出在 opens_spider 方法的名字拼写错误上。在 scrapy 中,该方法的正确名称是 open_spider,而不是 opens_spider。

修改后的代码如下:

class mysqlPipeline(object):     conn = None     cursor = None      # 连接数据库     def open_spider(self, spider):         self.conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', password='123456', db='test',charset='utf8')      def process_item(self, item, spider):         self.cursor = self.conn.cursor()         try:             self.cursor.execute('insert into qiubai values("%s","%s")' % (item["author"], item["content"]))             self.conn.commit()         except Exception as e:             print(e)             self.conn.rollback()  # 回滚         return item      def close_spider(self, spider):         self.cursor.close()         self.conn.close()

更正了 open_spider 方法的名称后,数据库连接将正常工作,你就可以将数据存储到 mysql 数据库中了。

上一篇: 错误:python 包安装时的外部管理环境
下一篇: 制作网页时遇到“UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf”错误,该如何解决?

作者:admin @ 24资源网   2025-01-14

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。