问答详情
源自:2-8 保存数据

我保存到mysql里,想问下在哪里执行close连接的操作呢?process_item函数里关闭不行吧?关掉之后下条数据就插不进去了

# noinspection PyUnresolvedReferences
import pymysql
# noinspection PyUnresolvedReferences
from douban.settings import mysql_db_name,mysql_password,mysql_table_name,mysql_host,mysql_username


class DoubanPipeline:
    def __init__(self):
        db = pymysql.connect(mysql_host, mysql_username, mysql_password, mysql_db_name)
        cursor = db.cursor()
        self.db = db
        self.cursor = cursor

    def process_item(self, item, spider):
        insert_sql = '''INSERT INTO `douban`.`top250` 
                        (`serial_number`, `movie_name`, `introduce`, `star`, `evaluate`, `describe`) 
                        VALUES ({}, '{}', '{}', {}, '{}', '{}')'''.format(item['serial_number'],item['movie_name'],
                                                                           item['introduce'],item['star'],
                                                                           item['evaluate'],item['describe'])
        self.cursor.execute(insert_sql)
        self.db.commit()
        # self.cursor.close()
        # self.db.close()
        return item


提问者:botao555 2020-09-23 17:39

个回答

  • 慕圣0027805
    2021-02-23 16:13:59

    为什么要close呢?