python - Select(SQL语句中并未使用所有参数)

标签 python mysql web-scraping scrapy

您好,我的代码有问题,我想检查管道 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()

请问有什么想法吗?

最佳答案

SELECT count(*) FROM TBL WHERE SQL 中的语句仅返回 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。

关于python - Select(SQL语句中并未使用所有参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55756219/

相关文章:

javascript - PHP Chart Js加载Mysql及接口(interface)

python - 使用 BeautifulSoup 和 Python 抓取多个页面

python - 如何使用 bs4 在 python 中抓取单页应用程序网站

python - 在Python pandas DataFrame中对具有接近日期时间的记录进行分组

mysql - 事务会暂时阻止其他更新,还是只是隐藏它们?

python - 在 Python 中将自定义对象序列化为 JSON 的方法

MySQL 查询 : Return all rows with a certain value in one column when value in another column matches specific criteria

node.js - puppeteer 中的页面 cookie 不适用于保持登录

Python C 扩展 : Py_DECREF for PyList

python - 正则表达式问题求助