Search code examples
pythonmysqlappendpymysql

Insert first 3 elements of 2D array into MySql Database


I have a list with data such as

infoarray[['1.', 'Name1', 'details1, '...', '...', '....'], ['2.', 'Name2, 'details2', '...', '...', '...'], ['3.', 'Name3', 'details3', '...', '...', '...']...]

I simply want to add the first 3 entries into a database table with the format

[PLACE],[NAME],[DETAILS]

Should be relatively simple. The data is already sorted, I would just simply have to append the first 3 elements of each inner array into my database. I tried the following code but I am getting an error.

//using pymysql

cur = conn.cursor()

cur.executemany("""
    INSERT INTO 
        myTable
        (place, name, details)
    VALUES
        (%s, %s, %s)
""", infoarray)
db.commit()

cur.close()
conn.close()

The error is "TypeError: not all arguments converted during string formatting" which is assume means that my formatting is wrong. I am relatively new to python, so I am very familiar with the nuances of using pymysql.


Solution

  • This happens because you are formatting 3 values in your query, but passing more than 3 elements per arra yitem.

    Try changing your executemany call to:

    cur.executemany("""
        INSERT INTO 
            myTable
            (place, name, details)
        VALUES
            (%s, %s, %s)
    """, [a[:3] for a in infoarray])
    

    This way you will get only the first 3 elements in each array item and pass it to executemany