Python Forum
Need help saving data into MySQL database - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Need help saving data into MySQL database (/thread-10724.html)



Need help saving data into MySQL database - reezalaq - Jun-03-2018

I'm trying to save API data into MySQL database but not sure why this isn't working Confused :

from aliexpress_api_client import AliExpress
import pymysql.cursors

aliexpress = AliExpress('9420', 'bazaarmaya')

data = aliexpress.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice'], 'drones')

#print(data)

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='Kradz579032!!',
                             db='aliexpressapidb',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
try:
    with connection.cursor() as cursor:
        sql_template ="""
        INSERT INTO producttable (productId, productTitle, salePrice, originalPrice )
            SELECT * FROM (SELECT %(productId)s, %(productTitle)s, %(salePrice)s, %(originalPrice)s) AS tmp
            WHERE NOT EXISTS (
                SELECT productId FROM producttable WHERE productId = %(productId)s
            )
            LIMIT 1;
        """

        for product in data:
            #print('%s %s %s %s' % (product['productId'], product['productTitle'], product['salePrice'], product['originalPrice']))

            cursor.execute(sql_template, {product['productId'], product['productTitle'],
                                          product['salePrice'], product['originalPrice']})


        connection.commit()

finally:
    connection.close()
ERROR :

Error:
/Users/reezalaq/PycharmProjects/Aliexpress/venv/bin/python /Users/reezalaq/Downloads/newali/script.py Traceback (most recent call last): File "/Users/reezalaq/Downloads/newali/script.py", line 28, in <module> print('%s %s %s %s' % (product['productId'], product['productTitle'], product['salePrice'], product['originalPrice'])) TypeError: string indices must be integers Process finished with exit code 1