Search code examples
pythonmysqllistinsertpymysql

Import multiple lists in MySQL using pymysql (Python)


I am trying to insert multiple lists at once in MySQL using pymysql library. I have tried the following:

import pymysql

db = pymysql.connect(host="ipaddress", user="me", passwd="password", db="test") 
cursor=db.cursor()

list1=[3.1, 4.5, 8.3]
list2=[1.2, 3.4, 5.2]
list3=[2.4, 6.5, 6.9]

cursor.executemany("insert into table (var1,var2,var3) values (%f, %f, %f)", [list1,list2,list3])
db.commit()
db.close()

But I get error. What I am doing wrong?. How should I be doing it?


Solution

  • I have found out where the problem was. The solution is the following:

    cursor.executemany("insert into table (var1,var2,var3) values (%s, %s, %s)", [list1,list2,list3])
    

    Instead of values (%f, %f, %f) it should be values (%s, %s, %s). I have tested it and it works. Unfortunately cannot explain why the query should be written in this way as I am working with numeric lists and not strings.