Posts tagged with “mysqldb”

Tue 29 Jun

python-mysqldb: execute() first

While working on implementing a schema-free, MySQL-backed data store (thanks, Bret Taylor!), I ran into a problem with using MySQLdb to access the database. I'll eventually post the code I wrote up on this site so others can see my example, but for now the following will suffice. When performing a SELECT, I would get the following error upon attempting to fetch my results.

Incorrect Python:
q = "SELECT body FROM entities WHERE id='%s'" % (entity_id)
entity = self.conn.cursor().fetchone()

File "", line 93, in get
entity = self.conn.cursor().fetchone()
File "/usr/lib/pymodules/python2.6/MySQLdb/", line 340, in fetchone
File "/usr/lib/pymodules/python2.6/MySQLdb/", line 70, in _check_executed
self.errorhandler(self, ProgrammingError, "execute() first")
File "/usr/lib/pymodules/python2.6/MySQLdb/", line 35, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: execute() first

The issue was using two separate cursor objects. Here's the corrected code:
c = self.conn.cursor()
q = "SELECT body FROM entities WHERE id='%s'" % (entity_id)
entity = c.fetchone()