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