Search code examples
pythonmysql-connector-python

Why would cursor.with_rows return `True` but fetch_one return `None`?


Given this partial function (and Python 2.7, mysql-connector 2.1.6):

def get_target_item(self, query, key):
    self._target_query.execute(query, (key,))
    if self._target_query.with_rows:
        raw_item = self._target_query.fetchone()

I expected raw_item to always be non-None, but it turns out that it is sometimes None.

If I add this:

        if not raw_item:
            print "Could not find find target item for query {0} and key {1}".format( query, key )

I can see this gets printed sometimes. And if I run the same query myself, I can see that the query does not return rows for the specified key. So why does with_rows suggest that it does?


Solution

  • The following is what the documentation for .with_rowssays:

    Returns whether the cursor could have rows returned

    This property returns True when column descriptions are available and possibly also rows, which will need to be fetched.

    As you can see, as long as the description attribute of the cursor is not None, with_rows will return True.

    If you are using a buffered cursor, you can check the cursor's rowcount attribute to make sure that it is greater than 0. That should constitute a better check.

    I hope this proves useful.