Problem inserting into MySQL database from Python

I am having trouble inserting a record into a MySQL database from python. This is what I do.

def testMain2(): conn = MySQLdb.connect(charset='utf8', host="localhost", user="root", passwd="root", db="epf") cursor = conn.cursor() tableName = "test_table" columnsDef = "(export_date BIGINT, storefront_id INT, genre_id INT, album_id INT, album_rank INT)" exStr = """CREATE TABLE %s %s""" % (tableName, columnsDef) cursor.execute(exStr) #Escape the record values = ["1305104402172", "12", "34", "56", "78"] values = [conn.literal(aField) for aField in values] stringList = "(%s)" % (", ".join(values)) columns = "(export_date, storefront_id, genre_id, album_id, album_rank)" insertStmt = """INSERT INTO %s %s VALUES %s""" % (tableName, columns, stringList) cursor.execute(insertStmt) cursor.close() conn.close() 

A table has been created, but there is nothing in the table. I can run the INSERT successfully in a terminal with the same credentials.

Any suggestions on what I might be doing wrong?

+4
source share
1 answer

You have not completed a transaction.

 conn.commit() 

(The MySQLdb library sets autocommit to False when connecting to MySQL. This means that you need to manually call a commit, or your changes will never go to the database.)

+9
source

All Articles