简体   繁体   中英

PYTHON-MYSQL : How to insert multiple data into MySQL database?

This script doesn't produce any error when I ran it but it only insert single item into database. If I do print(imageUrl), the are more than 12 items.

    from aliexpress_api_client import AliExpress
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='root', password='Kradz579032!!',
                              host='127.0.0.1',
                              database='aliexpressapidb')
cursor = cnx.cursor()

add_data = ("INSERT INTO producttable "
               "(productId, productTitle, salePrice, originalPrice, imageUrl) "
               "VALUES (%s, %s, %s, %s, %s)")

aliexpress = AliExpress('9420', 'bazaarmaya')
data = aliexpress.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'], 'pillow')
for product in data['products']:
    productId = product['productId']
    productTitle = product['productTitle']
    salePrice = product['salePrice']
    originalPrice = product['originalPrice']
    imageUrl = product['imageUrl']


data_insert = (productId, productTitle, salePrice, originalPrice, imageUrl)

cursor.execute(add_data, data_insert)





cnx.commit()

cursor.close()
cnx.close()

You are not executing for every iteration of your forEach loop.

Try to move the data_insert = (productId, productTitle, salePrice, originalPrice, imageUrl) and cursor.execute(add_data, data_insert) inside the loop like this:

from aliexpress_api_client import AliExpress
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='root', password='Kradz579032!!',
                              host='127.0.0.1',
                              database='aliexpressapidb')
cursor = cnx.cursor()

add_data = ("INSERT INTO producttable "
               "(productId, productTitle, salePrice, originalPrice, imageUrl) "
               "VALUES (%s, %s, %s, %s, %s)")

aliexpress = AliExpress('9420', 'bazaarmaya')
data = aliexpress.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'], 'pillow')
for product in data['products']:
    productId = product['productId']
    productTitle = product['productTitle']
    salePrice = product['salePrice']
    originalPrice = product['originalPrice']
    imageUrl = product['imageUrl']
    data_insert = (productId, productTitle, salePrice, originalPrice, imageUrl)
    cursor.execute(add_data, data_insert)




cnx.commit()

cursor.close()
cnx.close()

That should fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM