Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

python - Why would MySQL execute return None?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...