3

I have a mysql db that I manage via MAMP (using port 3306, server is on port 80). I have downloaded and installed the mysql-connector-python library from Oracle and am trying to access and manipulate the db. Curiously, following the tutorials at http://dev.mysql.com/doc/connector-python/en/connector-python-tutorial-cursorbuffered.html, I'm able to run a query to insert new records into a specific table (as long as I issue the .commit() method on my connector).

However, I can't seem to retrieve any data with a simple select command. So the query, "Select * from Assignments" returns None.

query = ('''SELECT title,description FROM  `Assignments` LIMIT 0 , 30''')

cursor = cnx.cursor()
result = cursor.execute(query)
print "result:",result

#All assignment info
for (title, description) in results:
    print title, description

I keep getting the error, "TypeError: 'NoneType' object is not iterable". I believe this has to do with the fact that the result of the executed query is None. B/c I'm able to commit update and insert changes to the db, I know that I'm connecting just fine. Why can't I run a simple SELECT command and get something?

3 Answers 3

6

You should use a MySQLCursor.fetchall method to get the results .

cursor.execute(query)
rows = cursor.fetchall()

or

cursor.execute(query)
head_rows = cursor.fetchmany(size=2)
remaining_rows = cursor.fetchall()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Alexander! This worked beautifully. I wonder why it's not mentioned on the documentation tutorial page (dev.mysql.com/doc/connector-python/en/…). What's there is what results in the error (for me).
4

You don't need to call fetchall, if you look at the docs you will see there is no assignment to the return value of the execute call as the method returns None, you just execute and then iterate over the MySQLCursor/cursor object:

query = ('''SELECT title,description FROM  `Assignments` LIMIT 0 , 30''')

cursor = cnx.cursor()

# forget assigning, just execute
cursor.execute(query)

# iterate over the cursor 
for (title, description) in cursor:
    print title, description

Comments

0

If you want to use mycursor.fetchone() then do the following:

   myresult = mycursor.fetchone()
   row_count = mycursor.rowcount
    
   if row_count == 1:
      row_id = myresult[0]
      print(row_id)

Basically you can access the items as an array like myresult[0], myresult[1] and so on....

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.