数据库插入失败,没有任何错误

2024-09-30 08:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

我正在使用scray和dataset(https://dataset.readthedocs.io/en/latest/quickstart.html#storing-data),它是sqlalchemy的顶层,试图将数据加载到sqllite表中,作为Sqlalchemy : Dynamically create table from Scrapy item的后续操作。在

使用数据集包,我有:

class DynamicSQLlitePipeline(object):

    def __init__(self,table_name):

        db_path = "sqlite:///"+settings.SETTINGS_PATH+"\\data.db"
        db = dataset.connect(db_path)
        self.table = db[table_name].table


    def process_item(self, item, spider):

        try:
            print('TEST DATASET..')
            self.table.insert(dict(name='John Doe', age=46, country='China'))
            print('INSERTED')
        except IntegrityError:
                print('THIS IS A DUP')
        return item

在运行我的spider之后,我看到打印语句打印在try except块中,没有错误,但是在完成之后,我查看表并看到屏幕截图。表中没有数据。我做错什么了?在


Tags: 数据pathnameselfdbdatadeftable
2条回答

你发布的代码对我来说不起作用:

TypeError: __init__() takes exactly 2 arguments (1 given)

这是因为__init__方法需要一个未被传递的table_name参数。您需要在pipeline对象中实现from_crawler类方法,类似于:

^{pr2}$

这将创建一个使用spider名称作为表名的管道对象,当然可以使用任何您想要的名称。在

{{cd4}也应该用^{cd5}代替}

之后,数据被存储: enter image description here

可能是数据库连接有问题。把你的这个片段放到一个尝试中,除了检查问题。在

try:
   db_path = "sqlite:///"+settings.SETTINGS_PATH+"\\data.db"
   db = dataset.connect(db_path)
   self.table = db[table_name].table
except Exception:
   traceback.exec_print()

相关问题 更多 >

    热门问题