Python MySQL Connector执行INSERT报错:Shopify抓取商品存入MySQL失败
报错诱发原因
- 核心原因是SQL占位符的键名与你解析得到的商品字典的key完全不匹配:你在INSERT语句中使用的占位符是
%(Name)s、%(Handle)s等大写开头的键名,但你parsejson方法生成的商品字典的key全是小写/小驼峰开头,比如name、handle,MySQL Connector无法在字典中找到对应key值,因此抛出找不到Name的报错。 - 额外逻辑错误:你已经将所有商品数据整理为
totals列表,外层却写了for p in totals的循环,循环内部又调用适合批量插入的executemany方法,属于重复逻辑,会导致数据重复插入或执行报错。 - 其他隐性错误:你定义的爬虫类名为
myScraper,但main函数中实例化时写成了Scraper,会触发类不存在的报错;downloadjson方法中调用了requests.get但代码开头没有导入requests库,也会触发报错。
修复方案
- 修正SQL语句的占位符,确保和你生成的商品字典key完全一致,同时检查你表字段的拼写(你原SQL中的
Descritpion存在拼写错误,若表字段实际为Description需要同步修正) - 去掉外层多余的
for p in totals循环,直接调用executemany批量插入totals列表 - 修正类名引用错误,补充导入缺失的
requests库 - 增加事务回滚逻辑,插入失败时避免脏数据写入
可选优化:你当前代码中遍历商品图片时只会保留最后一张图片的URL,若需要存储商品所有图片,可调整parsejson方法中图片和变体的对应逻辑。
修正后的核心代码片段
导入部分修正
import json import pandas as pd import mysql.connector import requests # 补充导入缺失的requests库 import ScraperConfig as conf
main函数实例化修正
def main(): scrape = myScraper('https://www.someshopifysite.com/') # 修正类名引用错误 results = [] # 其余main函数代码保持不变
数据库插入逻辑修正
if __name__ == '__main__': db = mysql.connector.connect( user=conf.user, host=conf.host, passwd=conf.passwd, database=conf.database) cursor = db.cursor() products = main() totals = [item for i in products for item in i] # 修正SQL占位符和字段拼写,和字典key完全对应 sql = """INSERT INTO `table` (`Name`, `Handle`, `Description`, `VariantId`, `CreatedDateTime`, `ProductType`, `VendorProductId`, `ImageURL`, `Price`, `SalePrice`, `Available`, `UpdatedDateTime`, `Vendor`) VALUES (%(name)s, %(handle)s, %(description)s, %(productVariantId)s, %(createdDateTime)s, %(productType)s, %(vendorProductId)s, %(imageURL)s, %(price)s, %(salePrice)s, %(available)s, %(updatedDateTime)s, %(vendor)s)""" try: cursor.executemany(sql, totals) db.commit() # 插入成功再提交 print(f'成功插入{cursor.rowcount}条数据到DB') except mysql.connector.Error as err: db.rollback() # 插入失败回滚 print("Something went wrong: {}".format(err)) finally: cursor.close() db.close()
内容的提问来源于stack exchange,提问作者Chris Brasch
相关产品推荐
相关产品推荐

