Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在通过管道从spider插入数据之前清空表,以避免重复_Python_Mysql_Sql_Scrapy - Fatal编程技术网

Python 在通过管道从spider插入数据之前清空表,以避免重复

Python 在通过管道从spider插入数据之前清空表,以避免重复,python,mysql,sql,scrapy,Python,Mysql,Sql,Scrapy,大家好,我的项目管道中有这段代码,它工作得很好,它会自动将刮取的数据添加到我的mysql数据库中。我想知道是否有可能在将更新的数据放入表之前清空表 我曾尝试添加一个“Truncate”命令,但没有成功,您将如何执行该操作?这是为了避免更新时表中出现重复项。我希望管道像这样工作-如果找到了项,则截断表,然后向表中插入新数据 def process_item(self, item, spider): try: if 'BristolQualification'

大家好,我的项目管道中有这段代码,它工作得很好,它会自动将刮取的数据添加到我的mysql数据库中。我想知道是否有可能在将更新的数据放入表之前清空表

我曾尝试添加一个“Truncate”命令,但没有成功,您将如何执行该操作?这是为了避免更新时表中出现重复项。我希望管道像这样工作-如果找到了项,则截断表,然后向表中插入新数据

def process_item(self, item, spider):
        try:
            if 'BristolQualification' in item:
                self.cursor.execute("INSERT INTO Bristol(BristolCountry, BristolQualification) VALUES (%s, %s)",
                (item['BristolCountry'], "".join([s.encode('utf-8')
                for s in item['BristolQualification']])))
            elif 'BathQualification' in item:
                self.cursor.execute("INSERT INTO Bath(BathCountry, BathQualification) VALUES (%s, %s)",
                (item['BathCountry'], "".join([s.encode('utf-8')
                for s in item['BathQualification']])))
            elif 'USWQualification' in item:
                self.cursor.execute("INSERT INTO USW(USWCountry, USWQualification) VALUES (%s, %s)",
                (item['USWCountry'], "".join([s.encode('utf-8')
                for s in item['USWQualification']])))

            self.conn.commit()
            return item

        except MySQLdb.Error as e:
            print "Error %d: %s" % (e.args[0], e.args[1])

如果每个国家都是一个唯一的表,那么截断应该有效。或者,改为使用WHERE子句中国家/地区的主键进行更新。您是否能够修复此问题,或者仍然需要帮助?:)我没有让它工作,没有。我很想知道未来如何做。