pymysql的使用

import pymysql


class StoreSpiderPipeline(object):
    def __init__(self):
        # 连接数据库:
        self.coon = pymysql.connect(host='数据库ip', user='root', password='8888888', port=8888, db='88888')
        #创建游标对象
        self.cursor = self.coon.cursor()
        self.cursor.execute("create table IF NOT EXISTS klkl_4s_shop(city char(50), district char(50), company_name char(100), business char(100), phone char(50), adress char(50));")
        self.coon.commit()

    def process_item(self, item, spider):
        sql = 'insert into klkl_4s_shop(city,district,company_name,business,phone,adress) values (%s,%s,%s,%s,%s,%s)'
        try:
            self.coon.ping(reconnect=True)
            self.cursor.execute(sql, (item['city'], item['district'], item['company_name'], item['business'], item['phone'],item['adress']))
            self.coon.commit()
            print('klkl_4s_shop提交成功')
        except:
            self.coon.rollback()
            print('klkl_4s_shop提交失败')
        return item

 

posted @ 2019-02-20 11:56  年轻人——001  阅读(343)  评论(0编辑  收藏  举报