python scrapy 保存数据到mysql的坑(1064错误)

版权声明:本文为徐代龙原创文章,未经徐代龙允许不得转载。网络资源网站:xudailong.cc 福利网站:www.00reso.com 公众号:蛇崽网盘教程资源 https://blog.csdn.net/xudailong_blog/article/details/83211412

在将scrapy中的数据存储到mysql中,出现部分数据插入不进去的问题, 一直报:
在这里插入图片描述

You have an error in your SQL syntax;

mysql相对于mongo来说,对数据要严格些,有时候,很多SQL语句写对了,还是插不进去数据。针对上面的问题,我使用了一个pymysql中的方法file_count = pymysql.escape_string(item['file_content']),这样就成功的把数据插入到MySQL中了。

下面贴一下全部的代码:

class MysqlPipeline(object):

    def __init__(self):
        self.host = settings.DB_HOST
        self.port = settings.DB_PORT
        self.user = settings.DB_USER
        self.pwd = settings.DB_PWD
        self.name = settings.DB_NAME
        self.charset = settings.DB_CHARSET

        self.connect()

    def connect(self):
        self.conn = pymysql.connect(host=self.host,
                                    port=self.port,
                                    user=self.user,
                                    password=self.pwd,
                                    db=self.name,
                                    charset=self.charset)
        self.cursor = self.conn.cursor()

    def close_spider(self, spider):
        self.conn.close()
        self.cursor.close()

    def process_item(self, item, spider):
        try:
            print('在插入 ***************************************          ')
            # sql = 'insert into zb_contest_data(craw_date, cd_filename, cd_content, create_time) values("%s", "%s", "%s", "%s")' % (
            #     item['craw_date'], item['file_name'], str(item['file_content']), item['create_time'])
            file_count = pymysql.escape_string(item['file_content'])
            sql = 'insert into zb_contest_data(craw_date, cd_filename, cd_content, create_time) values("%s", "%s", "%s", "%s")' % (
                item['craw_date'], item['file_name'], file_count, item['create_time'])

            # sql = 'insert into zb_contest_data(craw_date, cd_filename, cd_content, create_time) values("%s", "%s", "%s", "%s")' % (
            #     item['craw_date'], item['file_name'], item['file_content'], item['create_time'])

            # 执行sql语句
            self.cursor.execute(sql)
            self.conn.commit()
            pass
        except Exception as e:
            print(e)
            pass
        return item

个人微信:hll643435675(备注:博客)

在这里插入图片描述

更多资源请访问:

https://blog.csdn.net/xudailong_blog/article/details/78762262

慕课视频教程:https://blog.csdn.net/xudailong_blog/article/details/82909611

猜你喜欢

转载自blog.csdn.net/xudailong_blog/article/details/83211412