4

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

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()

The table is created however nothing is in the table. I can run the INSERT statement successfully in Terminal with the same credentials.

Any suggestions on what I may be doing wrong?

5
  • post output here of insertStmt variable Commented May 22, 2011 at 18:02
  • Excuse me? Are you saying that printing insertStmt (not output of query exec) results in no output? Commented May 22, 2011 at 18:32
  • if that's the case then stringlist may be the culprit; can you print stringlist? Not a pythonista, you may want to post under python tag, this is likely a no brainer for experienced python user (apologies if that is you!) Commented May 22, 2011 at 18:35
  • et voila, @Dan, experienced python user to the rescue Commented May 22, 2011 at 18:37
  • I don't get any outputs or an error when I run the above code. Commented May 22, 2011 at 20:53

1 Answer 1

9

You haven't committed the transaction.

conn.commit()

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

Sign up to request clarification or add additional context in comments.

Comments

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.