0

I have been trying to insert into a MySQL database from python using the MySQLdb interface. While I have been able to successfully execute select queries, my insert queries do nothing. They return no errors, but also do not add anything to the database.

I simplified my program down to just this.

db = MySQLdb.connect(host='127.0.0.1',user=...,passwd=...,db=...)
cursor = db.cursor()
cursor.execute("""INSERT INTO user_event_log (username, major_event_id, minor_event_id, value, date) VALUES ('Test', 1, 1, '0.1', '2017-07-29')""")

Not sure if I am making a really dumb mistake, but I can't figure out why nothing is inserted.

0

2 Answers 2

2

You need to commit changes in database and close the database. Please follow below changes of code:

import MySQLdb

# Open database connection
db = MySQLdb.connect(host='127.0.0.1',user=...,passwd=...,db=...)

# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = """INSERT INTO user_event_log (username, major_event_id, minor_event_id, value, date) VALUES ('Test', 1, 1, '0.1', '2017-07-29')"""
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add a MySQLdb.commit() to your connection. (Source)

This is as simple as adding db.commit() to the end of your code.

Hope it helps!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.