Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would MySQL execute return None?

Tags:

python

sql

mysql

I am trying to query on a local MySQL database using Python's (3.4) MySQL module with the following code:

class databases():

  def externaldatabase(self):

  try:
    c = mysql.connector.connect(host="127.0.0.1", user="user",
                                password="password", database="database")
     if c.is_connected():
           c.autocommit = True
      return(c)
    except:
         return(None)
    d = databases().externaldatabase()
    c = d.cursor() 
    r = c.execute('''select * from tbl_wiki''')
    print(r) 
> Returns: None

As far as I can tell, the connection is successful, the database is composed of several rows but the query always returns the none type.

What instances does the MySQL execute function return None?

like image 784
Barry Brian Avatar asked May 24 '15 08:05

Barry Brian


1 Answers

Query executions have no return values.

The pattern you need to follow is:

cursor creation;
cursor, execute query;
cursor, *fetch rows*;

Or in python:

c = d.cursor()

c.execute(query)    # selected rows stored in cursor memory

rows = c.fetchall()    # get all selected rows, as Barmar mentioned
for r in rows:
    print(r)

Also some db modules allow you to iterate over the cursor using the for...in pattern, but triple-check that regarding mysql.

like image 163
rask004 Avatar answered Oct 19 '22 20:10

rask004