Home > database >  how apply conditional statement on sql query result in python
how apply conditional statement on sql query result in python

Time:08-19

In python , i want to apply following if condition on mysql result. but it is not able to compare the result, what i do?? In this code there is table named as 'mansih' but still it's not printing 'hello'.

dir=ptr.execute('show tables')
for i in ptr.fetchall():
    print(i)
    if i== 'mansih':
        print('hello')

the output of this code just printing the result of print(i). output is

('3432fddf',)
('dgdfdf232342334243432',)
('man456',)
('mansih',)

here i expect to print hello but it's not printed. so please provide any solution using which i can check whether given touple exist in database or not.

CodePudding user response:

As you can see in your comment:

('3432fddf',) ('dgdfdf232342334243432',) ('man456',) ('mansih',)

You get tuples, and not strings, from fetchall. It should work if you modify it to if i[0] == 'mansih':, so as to fetch the first element of the tuple – which is the string you expect.

Two important lessons from this are:

  1. You can use the (interactive, optionally) interpreter to test your outputs, and you should make sure that you understand what you see. This could spare you lots of head scratching.
  2. Take a look at documentation if something doesn't work as expected, to make sure you understand how your tools work.
  • Related