fishjoe
fishjoe

Reputation: 49

Python check sqlite data exits?

I wrote few lines of code to check if data exist in database as below:

def check_if_data_exists(self):
    with self.connection as mycur:
        result = mycur.execute(f'select 1 from Summary1 where "Date Time" = "20220722.2008";')
        for row in result:
            if row == (1,):
                print("yes its here")

When the data exists it successfully printed "yes its here". However if I wrote lines as this:

def check_if_data_exists(self):
    with self.connection as mycur:
        result = mycur.execute(f'select 1 from Summary1 where "Date Time" = "20220723.2008";')
        for row in result:
            if row == (1,):
                print("yes its here")
            else:
                print("No its not here")

It fails to print "No its not here". Instead the program just run with nothing happens. I'm using Pycharm by the way.

Anyone knows what's going on? how can I get the false conditioned result pls?

Alternatively, any better code better way to achieve the same result would be appreciated.

Many thanks.

Upvotes: 1

Views: 32

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522797

What is happening here is that in the event that no matching data be found, the result set is empty, and therefore the list which gets returned will be completely empty and also falsy. Try using this version:

def check_if_data_exists(self):
    with self.connection as mycur:
        result = mycur.execute("SELECT 1 FROM Summary1 WHERE \"Date Time\" = '20220723.2008'")
    if result:
        print("yes its here")
    else:
        print("No its not here")

Perhaps a more safe way to do this would be to use an exists query, and then just check the (single) boolean value returned:

def check_if_data_exists(self):
    with self.connection as mycur:
        mycur.execute("SELECT EXISTS (SELECT 1 FROM Summary1 WHERE \"Date Time\" = '20220723.2008')")
        row = mycur.fetchone()
        if row[0]:
            print("yes its here")
        else:
            print("No its not here")

In the second version above, you would always get back a result set with a single record and boolean value.

Upvotes: 1

Related Questions