Pymysql Insert Into not working

PythonMysqlEclipsePython 2.7Pymysql

Python Problem Overview


I'm running this from PyDev in Eclipse...

import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='userid', passwd='password', db='fan')
cur = conn.cursor()
print "writing to db"
cur.execute("INSERT INTO cbs_transactions(leagueID) VALUES ('test val')")
print "wrote to db"

The result is, at the top of the Console it says C:...test.py, and in the Console:

writing to db wrote to db

So it's not terminating until after the execute command. But when I look in the table in MySQL it's empty. A record did not get inserted.

First off, why isn't it writing the record. Second, how can I see a log or error to see what happened. Usually there should be some kind of error in red if the code fails.

Python Solutions


Solution 1 - Python

Did you commit it? conn.commit()

Solution 2 - Python

PyMySQL disable autocommit by default, you can add autocommit=True to connect():

conn = pymysql.connect(
    host='localhost',
    user='user',
    passwd='passwd',
    db='db',
    autocommit=True
)

or call conn.commit() after insert

Solution 3 - Python

You can either do

  • conn.commit() before calling close

or

  • enable autocommit via conn.autocommit(True) right after creating the connection object.

Both ways have been suggested from various people at a duplication of the question that can be found here: https://stackoverflow.com/questions/384228/database-does-not-update-automatically-with-mysql-and-python

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael TView Question on Stackoverflow
Solution 1 - PythonqmorganView Answer on Stackoverflow
Solution 2 - PythonSteely WingView Answer on Stackoverflow
Solution 3 - PythonSimeonView Answer on Stackoverflow