0

I have a condition to check in Python. If the condition satisfies, only then I have to go ahead and extract data from a table in my SQL database.

The below code is working perfectly and giving me the extracted data from the SQL database.

import mysql.connector
conn = mysql.connector.connect(user='XXXXXXX', 
            password='XXXXXXX',host='XXXXXXX',database='XXXXXXX')
cursor = conn.cursor()
cursor.execute("SELECT * FROM table where table.column = 'abc')
result = cursor.fetchall()
print (result)
conn.close()

Now, I am trying to use an IF Condition before fetching data from SQL database. But this gives me syntax error.

Please find a sample of what I am trying as mentioned below:

if(x == 'True'):
    (import mysql.connector
     conn = mysql.connector.connect(user='XXXXXXX', 
            password='XXXXXXX',host='XXXXXXX',database='XXXXXXX')
     cursor = conn.cursor()
     cursor.execute("SELECT * FROM table where table.column = 'abc')
     result = cursor.fetchall()
     print (result)
     conn.close())
else:
    print("X is false, cannot execute")

Please help how can I execute only with a condition satisfied.

1
  • Try removing the bracket before the import keyword Commented Oct 22, 2021 at 7:32

1 Answer 1

1
  1. You should remove parenthesis in if block. Such a parenthesis you should use only when you call methods in chain, for example:
mysql.connector.connect(user='XXXXXXX', password='XXXXXXX',host='XXXXXXX',database='XXXXXXX')

(
    mysql.
    connector.
    connect(user='XXXXXXX', password='XXXXXXX',host='XXXXXXX',database='XXXXXXX')
)
  1. If x condition returns Boolean output True/False, enough is:
if x:
    ....
else:
    ....
  1. If x condition returns Boolean output True/False, True is not equal 'True':
True == 'True'

# output
False
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Removing the <brackets> worked. Also, there was indentation to be done post <brackets> removal. Code is working now.

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.