【问题标题】:psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction blockpsycopg2.errors.InFailedSqlTransaction:当前事务被中止,命令被忽略直到事务块结束
【发布时间】:2020-12-03 19:38:20
【问题描述】:

我编写了一个scrapy程序来从站点抓取数据,如果我抓取到json文件或csv文件,程序会成功抓取,当我尝试抓取到我的postgres数据库时出现问题,下图显示我收到错误,我该如何解决这个错误:

def process_item(self, item, spider):
    """Save deals in the database.
    This method is called for every item pipeline component.
    """
    self.cur.execute("insert into Deals (Name,Deal_Url,Image_Url,Old_Price,Special_Price,Final_Price) values(%s,%s,%s,%s,%s,%s)",(item['Name'],item['Product_URL'],item['Image_URL'],item['Old_Price'],item['Special_Price'],item['Final_Price']))
    self.connection.commit()
    return item

【问题讨论】:

    标签: python python-3.x postgresql scrapy psycopg2


    【解决方案1】:

    当事务中的操作失败时,您需要回滚,除了修复恶意操作(可能试图访问 item 中不存在的任何值)之外,您还可以将插入语句包装在 try/except 块中:

    def process_item(self, item, spider):
        """Save deals in the database.
        This method is called for every item pipeline component.
        """
    
        try:
            self.cur.execute("insert into Deals (Name,Deal_Url,Image_Url,Old_Price,Special_Price,Final_Price) values(%s,%s,%s,%s,%s,%s)",(item['Name'],item['Product_URL'],item['Image_URL'],item['Old_Price'],item['Special_Price'],item['Final_Price']))
            self.connection.commit()
        except:
            self.connection.rollback()
        return item
    

    【讨论】:

    • 如何处理一些为空的值?没有数据被插入到我的数据库中,我认为它是导致错误的空值
    • 您可以使用默认值,而不是 item['Name'] 使用 item.get('Name', None)
    猜你喜欢
    • 2011-01-13
    • 2013-08-04
    • 2012-05-11
    • 2016-12-11
    • 1970-01-01
    • 2011-12-06
    • 2013-10-25
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多