Guest User

Untitled

a guest
Jul 16th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. import pymysql
  4. from .settings import *
  5.  
  6.  
  7. class SaveMysqlPipeline(object):
  8. def __init__(self):
  9. # 连接数据库
  10. self.conn = pymysql.connect(
  11. host=MYSQL_HOST,
  12. port=MYSQL_PORT,
  13. user=MYSQL_USER,
  14. password=MYSQL_PASSWD,
  15. database=MYSQL_DBNAME,
  16. charset='utf8')
  17. # 建立游标对象
  18. self.cursor = self.conn.cursor()
  19. self.conn.commit()
  20.  
  21. def process_item(self, item, spider):
  22.  
  23. # 查重处理
  24. self.cursor.execute("select * from xxx where xx = %s",
  25. item['xx'])
  26. # 是否有重复数据
  27. repetition = self.cursor.fetchone()
  28.  
  29. # 重复
  30. if repetition:
  31. pass
  32.  
  33. else:
  34. sql = "insert into tablename(xx) "values(%s)"
  35. params = (item['xx'])
  36. self.cursor.execute(sql, params)
  37. self.conn.commit()
  38.  
  39. return item
  40.  
  41. def close_spider(self, spider):
  42. self.cursor.close()
  43. self.conn.close()
Add Comment
Please, Sign In to add comment