pythonpostgresqlpsycopg2psql

Return True/False of EXISTS Postgres query not being recognized by IF statement


enter image description here

def track_exists():
      conn = psycopg.connect("dbname=postgres user=postgres password=***)
      cur = conn.cursor()
      sqltest = "SELECT EXISTS(SELECT 1 FROM CUSTOMERS  WHERE CUSTOMERS.PHONE = '608-888-8888')"
      cur.execute(sqltest)
      result = cur.fetchall()
      if result == [(True,)]:
            print("working")
            dosomething()
      elif result == "":
            print("not working")

When running this function in VS CODE the output returns exactly, [(True,)] to the screen . My if statement does not recognize this as being true and returns my "not working" statement. No matter what way I've tried different versions of true, IE "True:" , "(True)," "True," etc...

      phonestring = phone_str
      print (phonestring)
      conn = psycopg.connect("dbname=postgres user=postgres password=***)
      cur = conn.cursor()
      sqltest = "SELECT EXISTS(SELECT 1 FROM CUSTOMERS  WHERE CUSTOMERS.PHONE = (%s))"
      sqldata = (phonestring)
      cur.execute(sqltest,sqldata)
      result = cur.fetchone()
      if result == [(True,)][0]: 
            print("Customer Exists")
      elif result == [(False,)][0]:
            print("New customer")

Solution

  • Thank you very much @TurePålsson for your insight! I was able to get the code working by using the tuple "if result == [(True,)][0]:" However I still do not know exactly what this code is doing and why I need to specify a 0 or anything else for the second value.