JohnDotOwl
JohnDotOwl

Reputation: 3755

Optimising mysql insert query via python

db = MySQLdb.connect(host="xxx.xx.xx.x",   
                    user="xxx",       
                    passwd="xxx",  
                    db="xxxx")
for loop on json data:
    cursor = db.cursor()
    cursor.execute('Insert Query')
    db.commit() 
db.close()

Would it be possible for me to improve this query? I'm considering doing multiple cursor.execute before db.commit()

I'm unsure how db.commit() works and the importance of it.

I'm basically looping a json data and inserting it with a loop. I cannot avoid having multiple inserts.

Upvotes: 1

Views: 39

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169274

Depending on how json_data is structured you should be able to use .executemany():

db = MySQLdb.connect(host="xxx.xx.xx.x",   
                     user="xxx",       
                     passwd="xxx",  
                     db="xxxx")
cursor = db.cursor()
cursor.executemany('Insert Query',json_data)
db.commit()
cursor.close()
db.close()

Upvotes: 1

Related Questions