Search code examples
pythonsqlitevalidationresultset

How to check results returned from sqlite2 execute?


I am trying to check and validate the results of cursor.execute('SQL query'). Below is the way I am trying to do it.

def select_from_db(card_number, pin):
   conn = sqlite3.connect('card.s3db')
   cur = conn.cursor()
   cur.execute("SELECT * FROM card WHERE number=?", (card_number,))
   returned_account = cur.fetchone()
   if type(returned_account[1]) is not 'NoneType':
      if returned_account[1] == card_number and returned_account[2] == str(pin):
          return True
   conn.close()
   return False

The idea is that when there is no card number in the db the select_from_db should return False, and if there is a card with the card_number, then I need to check its pin as well. When card number and pin match, the function should return True, else it should return Falce.

This is a course project. It is not for production.


Solution

  • I took your code and edit it.
    The code check for None result and make sure that connection is closed. (using finally)

    import sqlite3
    def select_from_db(card_number, pin):
      try:
        conn = sqlite3.connect('card.s3db')
        cur = conn.cursor()
        cur.execute("SELECT * FROM card WHERE number=?", (card_number,))
        returned_account = cur.fetchone()
        if returned_account is None:
          return False
        else:
          return returned_account[1] == card_number and returned_account[2] == str(pin)
      finally:
        if conn:
          conn.close()