1
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.

5
  • INSERT INTO tab_name(col_list) VALUES (...),(...),(...),(...). Insert multiple values at once. Commented Mar 4, 2016 at 20:59
  • @lad2025 I cant do that, the Loop is a must. I just have to do multiple Insert, cant help it. Commented Mar 4, 2016 at 21:00
  • Is Insert Query a string? because you can always create a string the way you want. and send the execute every 10 values or something. Commented Mar 4, 2016 at 21:02
  • @JuanCarlosOropeza It's not a string. It has %s in value Commented Mar 4, 2016 at 21:06
  • Then maybe you could Improve your question with a more clear sample. Commented Mar 4, 2016 at 21:12

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Can I do data processing in the sql statement value %s eg. str(%s)
No you cannot do it in that way. There may be another way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.