We help IT Professionals succeed at work.

How can I check the result of mysql query in python?

mickt
mickt asked
on
155 Views
Last Modified: 2016-09-25
I've seen lines like op.execute("CREATE LANGUAGE plpgsql") in other scripts in my system so thought I could do similar with the following.

op.execute("SHOW TABLES LIKE 'table_name'")

How can I check the result from this and then do stuff based on existence or not?

I tried result = op.fetchone() but this is incorrect.
  AttributeError: 'module' object has no attribute 'fetchone'

and
  if not op.execute("SHOW TABLES LIKE 'agents'"):
Comment
Watch Question

Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

Commented:
Server version: 5.6.31-ndb-7.4.12-cluster-gpl

Multiple DB and all working.

Trying to do/not do something based on the existence of a table.
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
I believe you have to process 'SHOW TABLES' and similar queries just like a SELECT query because that is what they are.

Author

Commented:
Sorry, I'm not following, can you please clarify for me?

Author

Commented:
I cam across this too.

    cursor.execute("SHOW TABLES LIKE 'table_name'")
    result = cursor.fetchone()
    if result:
        "There is a table named table_name."
    else:
        do stuff

but it complains about cursor
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
Glad you got it figured out.  I had to get some sleep.

Author

Commented:
Answers question.