Search code examples
pythonmysqlflaskflask-mysql

How to make this Flask-mysql insert commit?


I'm still using Flask-mysql.

I'm getting the database context (the mysql variable) just fine, and can query on the database / get results. It's only the insert that is not working: it's not complaining (throwing Exceptions). It returns True from the insert method.

This should be done inserting the record when it commits, but for some reason, as I watch the MySQL database with MySQL Workbench, nothing is getting inserted into the table (and it's not throwing exceptions from the insert method):

I'm passing in this to insertCmd:

"INSERT into user(username, password) VALUES ('test1','somepassword');"

I've checked the length of the column in the database, and copied the command into MySQL Workbench (where it successfully inserts the row into the table).

I'm at a loss. The examples I've seen all seem to follow this format, and I have a good database context. You can see other things I've tried in the comments.

def insert(mysql, insertCmd):
     try:
        #connection = mysql.get_db()
        cursor = mysql.connect().cursor()
        cursor.execute(insertCmd)
        mysql.connect().commit()
        #mysql.connect().commit
        #connection.commit()
        return True
     except Exception as e:
        print("Problem inserting into db: " + str(e))
        return False

Solution

  • You need to keep a handle to the connection; you keep overriding it in your loop.

    Here is a simplified example:

    con = mysql.connect()
    cursor = con.cursor()
    
    def insert(mysql, insertCmd):
         try:
            cursor.execute(insertCmd)
            con.commit()
            return True
         except Exception as e:
            print("Problem inserting into db: " + str(e))
            return False
    

    If mysql is your connection, then you can just commit on that, directly:

    def insert(mysql, insertCmd):
      try:
        cursor = mysql.cursor()
        cursor.execute(insertCmd)
        mysql.commit()
        return True
      except Exception as e:
        print("Problem inserting into db: " + str(e))
        return False
      return False