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
相關文章
相關標籤/搜索