vendredi 22 octobre 2021

Use IF condition in Python to Import Data from SQL Table (or Import Data from SQL table only when condition satisfies in Python)

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.

Aucun commentaire:

Enregistrer un commentaire