You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scrapy管道存MySQL报错:ProgrammingError参数不足

解决mysql.connector.errors.ProgrammingError: Not enough parameters for the SQL statement错误

错误原因分析

你的代码存在两个核心问题:

  • 循环逻辑错误:rows是单条爬虫数据的字段元组,你用for row in rows遍历会逐个取出单个字段值传入execute,但SQL语句需要12个参数,每次仅传1个必然触发参数不足的错误。
  • 字段顺序不匹配:SQL插入语句的字段顺序和rows里的字段顺序不一致,即便修复循环,也会导致数据插入到错误列中。

修正后的SaveToMysqlPipeline代码

class SaveToMysqlPipeline:
    def __init__(self):
        self.con = mysql.connector.connect(
            host="localhost",
            user="root",
            password="09.02girl",
            database="books",
        )
        self.cur = self.con.cursor()
        self.cur.execute("""
        CREATE TABLE IF NOT EXISTS books(
        id int NOT NULL auto_increment,
        url VARCHAR(225),
        title text,
        product_type VARCHAR(255),
        price_excl_tax DECIMAL,
        price_incl_tax DECIMAL,
        tax DECIMAL,
        price DECIMAL,
        availability VARCHAR(255),
        num_reviews VARCHAR(255),
        stars VARCHAR(255),
        category VARCHAR(225),
        description text,
        PRIMARY KEY(id)
        )

        """)

    def process_item(self, item, spider):
        # 调整字段顺序,与SQL插入语句的字段顺序完全对应
        row = (
            item['url'], item['title'], item['product_type'], item['price_excl_tax'], 
            item['price_incl_tax'], item['tax'], item['price'], item['availability'],
            item['num_reviews'], item['stars'], item['category'], item['description']
        )
        sql = """INSERT INTO books(
            url, title, product_type, price_excl_tax, price_incl_tax, tax, 
            price, availability, num_reviews, stars, category, description
        ) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
        # 直接传入完整元组,无需循环
        self.cur.execute(sql, row)
        self.con.commit()
        return item

    def closespider(self, spider):
        self.cur.close()
        self.con.close()

关键修正点

  1. 移除遍历rows的for循环,直接将完整字段元组作为参数传给execute,确保参数数量与SQL中%s的数量一致。
  2. 调整row元组内的字段顺序,使其完全匹配SQL插入语句中定义的字段顺序(例如将item['price']移到tax之后、availability之前)。
  3. 格式化SQL语句,让字段列表更清晰,便于核对顺序。

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 23:48:19