Simon Brix
Simon Brix

Reputation: 102

Can't commit mysql query from Python

I'm trying to get a small Flask app working that writes to a MySQL database, but it seems like the database commit isn't working and I have no idea why.

from flaskext.mysql import MySQL

mysql = MySQL()
mysql.init_app(app)

app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'eggsited'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

conn = mysql.connect()
cursor = mysql.connect().cursor()

cursor.execute('insert into user (id, first_name, last_name) values (%s, %s, %s)', ['324325', 'Kristoffer', 'Nielsen'])
conn.commit()

That's the part that deals with inserting values into my table. I know that my connection is working since I can do select statements and list the results from those and the execute statement is working too, because when I insert a new row directly in mysql the auto incremented id field has been incremented. So it must be the commit command that isn't actually committing the execute statement, but I have no idea why.

Is there something obvious that I have missed?

Upvotes: 0

Views: 1757

Answers (1)

Bee Kay
Bee Kay

Reputation: 166

From this question: MySQL not updating after calling connection.commit() with Flask (WORKING)

In the third last line of your code, change it from cursor = mysql.connect().cursor() to cursor = conn.cursor(). This will ensure that the cursor uses the existing connection to database (from the previous line of code), instead of creating a new MySQL connection.

Upvotes: 5

Related Questions