[英]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.
如果我打印(imageUrl),则超过12个项目。
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. 您不会在forEach循环的每个迭代中都执行。
Try to move the data_insert = (productId, productTitle, salePrice, originalPrice, imageUrl)
and cursor.execute(add_data, data_insert)
inside the loop like this: 尝试在
data_insert = (productId, productTitle, salePrice, originalPrice, imageUrl)
内移动data_insert = (productId, productTitle, salePrice, originalPrice, imageUrl)
和cursor.execute(add_data, data_insert)
,如下所示:
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. 那应该解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.