【问题标题】:Select (Not all parameters were used in the SQL statement)选择(并非所有参数都在 SQL 语句中使用)
【发布时间】:2019-09-09 09:25:25
【问题描述】:

您好,我的代码有问题,我想检查管道 process_item 中的重复 ID,如果没有重复的 id,我将在表中插入项目

这是我的代码

def process_item(self, item, spider):
    if isinstance(item, GPHM):
        t = (item['hm_title'],)
        rows_affected = self.curr.execute('SELECT 
COUNT(hm_articode) from saleitems_hm WHERE hm_articode=?', t)
        rows_affected = self.curr.rowcount

        if rows_affected > 1:
            global item_countHM 
            item_countHM += 1
            self.store_db(item)
    return item


def store_db(self, item):
    self.curr.execute("""insert into saleitems_hm values (%s, %s, %s, %s, %s, %s)""", (
            item['1'],
            item['2'],
            item['3'],
            item['4'],
            item['5'],
            item['6']
        ))
    self.conn.commit()

有什么想法吗?

【问题讨论】:

    标签: python mysql web-scraping scrapy


    【解决方案1】:

    SQL 中的SELECT count(*) FROM TBL WHERE 语句仅返回 1 行,即结果集中所有行的计数。现在查看这部分代码:

    rows_affected = self.curr.execute('SELECT 
    COUNT(hm_articode) from saleitems_hm WHERE hm_articode=?', t)
    rows_affected = self.curr.rowcount
    
    if rows_affected > 1:
        global item_countHM 
        item_countHM += 1
        self.store_db(item)
    

    rowcount 返回受影响的行数,在这种情况下为 1 或 -1。 row_affected 永远不会大于 1,并且 if 条件下的代码永远不会被执行。您可以使用fetchone 来获取实际计数。检查下面的代码:

    r = self.curr.fetchone('SELECT 
    COUNT(hm_articode) from saleitems_hm WHERE hm_articode= %s', t)
    is_duplicate = r[0] > 1
    
    if not is_duplicate:
        global item_countHM 
        item_countHM += 1
        self.store_db(item)
    

    请注意,如果条件发生更改,因为您要插入非重复记录。 Count(*) 大于 1 表示重复记录。

    【讨论】:

    • 嗨@joshi 我尝试了你的代码,但我仍然收到错误 self.curr.execute('SELECT COUNT(hm_articode) from saleitems_hm WHERE hm_articode=?', t) mysql.connector.errors。 ProgrammingError: SQL 语句中并未使用所有参数
    • 尝试使用 %s 进行字符串格式化。检查修改后的代码。
    猜你喜欢
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2020-12-12
    • 1970-01-01
    • 2020-05-25
    相关资源
    最近更新 更多