cikatomo
cikatomo

Reputation: 1632

How to use SQlite NULL inside function default parameter?

Id like to get domains from sqlite database where ip is NULL. I also want to make function so I can get domains with specific IPs in the future. I wrote function like this:

def get_domains(self, ip=None):
    """gets all the domains from domain table

    Keyword Arguments:
        ip {str} -- IP of the domain (default: {None})

    Returns:
        sqlite3.Row -- rows of the selected domains
    """
    sql = "SELECT domain FROM domains WHERE ip = ?"
    try:
        self.cursor.execute(sql, (ip,))
        rows = self.cursor.fetchall()
        return rows
    except Error as e:
        print(e)

but it returns no rows. It works when I test with other values, but can't make it to read WHERE ip = null. How do I return rows where default ip is null?

Upvotes: 0

Views: 53

Answers (1)

GMB
GMB

Reputation: 222672

You can't check for nullness with the equality operator; for this you need special expression IS NULL. Some databases offer a null-safe operator for equality (typically, MySQL has <=>, Postgres supports the standard IS [NOT] DISTINCT FROM). SQLite offers IS for that.

SELECT domain FROM domains WHERE ip IS ?

Upvotes: 1

Related Questions