插入错误 Python MySQL 连接器:执行操作失败

Posted

技术标签:

【中文标题】插入错误 Python MySQL 连接器:执行操作失败【英文标题】:INSERT Error Python MySQL Connector: Failed executing the operation 【发布时间】:2021-12-05 02:45:27 【问题描述】:

我正在使用 products.json 页面抓取 shopify 商店。尝试使用 Python 连接器将抓取的产品插入我的 mysql 数据库,但遇到以下错误:

出了点问题:执行操作失败; b'Name'

代码如下:

import json
import pandas as pd
import mysql.connector
import ScraperConfig as conf

class myScraper():

    def __init__(self, baseurl):
        self.baseurl = baseurl

    def downloadjson(self, page):
        r = requests.get(self.baseurl + f'products.json?limit=250&page=page', timeout=5)
        if r.status_code != 200:
            print('Bad status code', r.status_code)
        if len(r.json()['products']) > 0:
            data = r.json()['products']
            return data
        else:
            return

    def parsejson(self, jsondata):
        products = []

        for prod in jsondata:
            vendor = prod['vendor']
            name = prod['title']
            handle = prod['handle']
            createdDateTime = prod['created_at']
            description = prod['body_html']
            productType = prod['product_type']
            for images in prod['images']:
                vendorProductId = images['product_id']
                try:
                    imageURL = images['src']
                except:
                    imageURL = 'None'
            for variant in prod['variants']:
                item = 
                    'name': name,
                    'handle': handle,
                    'description': description,
                    'productVariantId': variant['id'],
                    'createdDateTime': createdDateTime,
                    'productType': productType,
                    'vendorProductId': vendorProductId,
                    'imageURL': imageURL,
                    'price': variant['price'],
                    'salePrice': variant['compare_at_price'],
                    'available': variant['available'],
                    'updatedDateTime': variant['updated_at'],
                    'vendor': vendor
                
                products.append(item)
        return products
        
def main():
    scrape = Scraper('https://www.someshopifysite.com/')
    results = []
    for page in range(1,2):
        data = scrape.downloadjson(page)
        print('Getting page: ', page)
        try:
            results.append(scrape.parsejson(data))
        except:
            print(f'Completed, total pages = page - 1')
            break
    return results

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]
    for p in totals:
        sql = """INSERT INTO `table` (`Name`, `Handle`, `Descritpion`, `VariantId`, `CreatedDateTime`, `ProductType`, `VendorProductId`, `ImageURL`, `Price`, `SalePrice`, `Available`, `UpdatedDateTime`, `Vendor`)          
        VALUES (%(`Name`)s, %(`Handle`)s, %(`Descritpion`)s, %(`VariantId`)s, %(`CreatedDateTime`)s, %(`ProductType`)s, %(`VendorProductId`)s, %(`ImageURL`)s, %(`Price`)s, %(`SalePrice`)s, %(`Available`)s, %(`UpdatedDateTime`)s, %(`Vendor`)s)"""
            
        try:
            cursor.executemany(sql, totals)
            
            print('Committed to DB')
        except mysql.connector.Error as err:
                    print("Something went wrong: ".format(err))
        db.commit() ```

【问题讨论】:

【参考方案1】:

从查询的以下和所有类似部分中删除反引号:

%(`Name`)s

通常我会删除反引号,除了引用映射到关键字的列名。

【讨论】:

试过了。不幸的是没有骰子。错误:出了点问题:执行操作失败; b'名字'

以上是关于插入错误 Python MySQL 连接器:执行操作失败的主要内容,如果未能解决你的问题,请参考以下文章

在python中使用mysql连接器插入数据

WebStorm创建Express项目如何连接MySQL执行增删改查

Python,MySql ON 重复键语法错误

pymysql 基操全套

java中执行access数据库插入错误!!!急!!!

MySQL 连接器/Python - 将 python 变量插入 MySQL 表